Home >Backend Development >PHP Tutorial >How to Append User Form Data to a TXT File Using PHP?
How to Write File Input to a TXT File in PHP
When creating a form to capture user input, it can be useful to save the data to a text file for storage or further processing. This can be accomplished with a few simple PHP commands.
PHP File
<?php if(isset($_POST['field1']) && isset($_POST['field2'])) { $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n"; $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX); if($ret === false) { die('There was an error writing this file'); } else { echo "$ret bytes written to file"; } } else { die('no post data to process'); } ?>
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>
Explanation
This solution automatically opens, writes, and closes the text file, handling the file I/O operations for you. Note that you can modify the target text file path as needed.
The above is the detailed content of How to Append User Form Data to a TXT File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!