Home >Backend Development >PHP Tutorial >How Can I Write Data from an HTML Form to a Text File Using PHP?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-27 12:05:15584browse

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>

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
}
?>

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!

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