Writing All Form Data into a File
$data[] = $_POST;
file_put_contents('formdata.txt',
serialize($data));
|
After a user fills out a form correctly, what do you do with the form data? A very intuitive approach that does not require too much setup on the server is to write the data into a file on the server.
Writing Form Data into a File (form-save.php; excerpt)
<?php
require_once 'stripFormSlashes.inc.php';
?>
...
<?php
if (isset($_POST['Submit']) &&
isset($_POST['fieldname']) &&
trim($_POST['fieldname']) != '') {
echo '<h1>Thank you for filling out this
form!</h1>';
$data = '';
$data = @file_get_contents('formdata.txt');
if ($data != '') {
$data = unserialize($data);
}
$data[] = $_POST;
file_put_contents('formdata.txt',
serialize($data));
} else {
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']); ?>">
...
</form>
<?php
}
?>
The preceding code contains a very naïve approach: All data is stored in a file on the server. When the form is submitted, the file is read in and unserialized into an array. Then, the form data is appended to the array. Finally, the array is serialized again and written back to the file.
Figure 4.3 shows this file in a text editor.

Of course, race conditions could occur and the file could be simultaneously read by two processes, which would result in just one of the two processes appearing in the file. To avoid this, you have to implement file locking as shown in Chapter 7, "Making Data Dynamic." |
|