When several people try to open the file at the same time, there is a problem. So the solution is to temporarily lock the file while PHP is opening and writing to it.
Use flock()
| Lock | Meaning |
|---|---|
| LOCK_SH | Shared lock for reading purposes |
| LOCK_EX | Exclusive lock for writing purposes |
| LOCK_UN | Release of a lock |
| LOCK_NB | Non-blocking lock |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Locking Files</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
if (isset($_POST['submit'])) {
process_form();
}
else {
display_form();// display form for the first time
}
function display_form() {
echo <<<HTML
<h2>Feedback Form</h2>
<form action = "$_SERVER[SCRIPT_NAME]" method="post">
Filename:
<input type="text" name="file" size="50" value="data/feedback.txt" />
<br />
Comments:
<textarea name="comments" rows="5" cols=""50">here are my comments.</textarea>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
HTML;
}
function process_form() {
$file = "$_POST[file]";
$data = stripslashes($_POST['comments']);
// open the file for reading
if ($fh = fopen("$file", 'ab')) {
// lock for writing
flock($fh, LOCK_EX);
// write the data
fwrite($fh, "$data\n");
// unlock after writing
flock($fh, LOCK_UN);
// close the file
fclose($fh);
echo "<p>Your feedback has been stored.</p>";
}
else {
echo "<p>Your feedback could not be stored.</p>";
}
echo "<p><a href=\"$_SERVER[SCRIPT_NAME]\">Try again?</a></p>\n";
echo "<p><a href=\"example_r.php\">
Do you want to read from the file?</a></p>\n";
}
?>
</p>
</body>
</html>
|