Home >Backend Development >PHP Tutorial >How to Append User Form Data to a TXT File Using PHP?

How to Append User Form Data to a TXT File Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 12:13:11942browse

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

  1. Form Processing: When the form is submitted, the myprocessingscript.php file is invoked.
  2. Input Validation: The PHP script checks if the required input fields, field1 and field2, are set.
  3. Data Preparation: The user input is concatenated into a single line of text, separated by a dash.
  4. File Writing: Using the file_put_contents function, the data is appended to the specified text file, /tmp/mydata.txt, with exclusive file locking.
  5. Error Handling: In case of any writing error, the script halts with an error message.
  6. Success Confirmation: If successful, the script displays the number of bytes written to the file.

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!

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