Home >Backend Development >PHP Tutorial >How to Write PHP Form Data to a TXT File?

How to Write PHP Form Data to a TXT File?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-24 10:11:14342browse

How to Write PHP Form Data to a TXT File?

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:

  • We wrote to /tmp/mydata.txt because the current working directory in your example is unknown.
  • file_put_contents is a preferred approach due to its simplicity.
  • For further information, refer to the file_put_contents documentation.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn