PHP's Simplified Approach to Writing Input Data to a Text File
In web development, it's often necessary to collect user input and store it in a persistent format. PHP provides an efficient solution for writing such input to a text file.
The Issue
A common challenge faced by developers is getting user input from an HTML form and writing it to a text file. To facilitate this process, we'll first create a simple form with two input fields (field1 and field2) and a submit button:
<form action="process.php" method="POST"> <input name="field1" type="text"> <input name="field2" type="text"> <input type="submit" name="submit" value="Save Data"> </form>
Next, we'll create a PHP script (process.php) to handle the form submission and write the input to a text file:
<?php if (isset($_POST['field1']) && isset($_POST['field2'])) { $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n"; file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX); } else { die('Missing required data'); } ?>
Solution
The file_put_contents() function simplifies the process of opening, writing, and closing a text file. It takes three parameters: the file path, the data to write, and any flags (e.g., FILE_APPEND to append to an existing file).
Additional Notes
The above is the detailed content of How Can PHP Simplify Writing User Input from an HTML Form to a Text File?. For more information, please follow other related articles on the PHP Chinese website!