Home > Article > Backend Development > How Can I Use PHP to Save Form Data to a Text File?
PHP: Writing Form Input to a Text File
Problem:
You have a form and want to capture the input entered in its fields and write it to a text file. However, your current solution fails to produce the desired result.
Solution:
To write form input to a text file, you can follow these steps:
Update HTML Form:
Ensure your form uses the "POST" method and includes the necessary input elements.
<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>
PHP Script:
<?php // Check if data is submitted if (isset($_POST['field1']) && isset($_POST['field2'])) { $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n"; // Use file_put_contents to write data to a text file $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX); if ($ret === false) { die("Error writing file"); } else { echo "$ret bytes written to file /tmp/mydata.txt"; } } else { die("No POST data to process"); } ?>
The above is the detailed content of How Can I Use PHP to Save Form Data to a Text File?. For more information, please follow other related articles on the PHP Chinese website!