How to Write Form Input to a TXT File with PHP
Are you trying to capture form input and save it to a TXT file using PHP? If you've encountered difficulties and a blank page, here's a detailed solution:
1. Form Structure:
The HTML form should have the correct "method" attribute:
<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:
The PHP script uses the file_put_contents function to write to a TXT 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'); }
3. File Permissions:
Ensure that the PHP script has write permissions to the target directory, such as /tmp in the example.
4. Alternative Approach:
You can also use the fopen() , fwrite() , and fclose() functions:
<?php $txt = "data.txt"; $fh = fopen($txt, 'w+'); if (isset($_POST['field1']) && isset($_POST['field2'])) { $txt=$_POST['field1'].' - '.$_POST['field2']; fwrite($fh,$txt."\n"); } fclose($fh);
5. Additional Notes:
The above is the detailed content of How to Write PHP Form Data to a TXT File?. For more information, please follow other related articles on the PHP Chinese website!