How Can I Write Data from an HTML Form to a Text File Using PHP?

Susan Sarandon
Release: 2024-11-27 12:05:15
Original
557 people have browsed it

How Can I Write Data from an HTML Form to a Text File Using PHP?

PHP: Writing Input Data to a Text File

In PHP, you can easily write data from an input field to a text file. Here's how to accomplish this task:

1. 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>
Copy after login

2. PHP Script:

<?php
if (isset($_POST['field1']) && isset($_POST['field2'])) { // Check if both fields are set
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n"; // Create the data
    $result = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX); // Write to the file
    if ($result === false) {
        die('Error writing to file'); // Handle error
    } else {
        echo "$result bytes written to file"; // Success
    }
} else {
    die('No post data to process'); // Handle error
}
?>
Copy after login

Explanation:

  • The HTML form collects user input in two fields (field1 and field2) and submits it to the processing script via the POST method.
  • The PHP script checks if both fields are set to prevent errors.
  • If the fields are set, it concatenates the input values with a hyphen and appends a newline character to create a data string.
  • The file_put_contents function opens the file data.txt for writing in append mode, locking it for exclusive access.
  • The data string is written to the file, and the number of bytes written is returned. If the write operation is successful, the result is echoed; otherwise, an error message is displayed.

The above is the detailed content of How Can I Write Data from an HTML Form to a Text File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template