Home >Backend Development >PHP Tutorial >How Can I Write Data from an HTML Form to a Text File Using PHP?
PHP: Writing Input Data to a Text File
In PHP, you can easily write data from an input field to a text file. Here's how to accomplish this task:
1. HTML Form:
<form action="myprocessingscript.php" method="POST"> <input name="field1" type="text" /> <input name="field2" type="text" /> <input type="submit" name="submit" value="Save Data" /> </form>
2. PHP Script:
<?php if (isset($_POST['field1']) && isset($_POST['field2'])) { // Check if both fields are set $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n"; // Create the data $result = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX); // Write to the file if ($result === false) { die('Error writing to file'); // Handle error } else { echo "$result bytes written to file"; // Success } } else { die('No post data to process'); // Handle error } ?>
Explanation:
The above is the detailed content of How Can I Write Data from an HTML Form to a Text File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!