A script in my website stopped working correctly about a month ago, even though I had not updated any code on the site. Turns out an flock() function is suddenly unable to get a lock on a file. Note, this worked perfectly for about a year then broke for no apparent reason. I isolated the problem code and found that while it will work without a session, it fails once I put it inside a session. Here are two test scripts. The first one works, the second fails. (The file _order_id.txt contains only a 5-digit number used for incrementing order id numbers.)

Also, BOTH scripts DO work on my local PC running EasyPHP, with PHP version 5.3.8. The live site runs 5.3.13. Has anyone seen this problem before? Thanks.

echo "<br>Flock Test without Sessions<br>";
$fp = fopen("order_id.txt", "r+");
if (flock($fp, LOCK_EX)) {
/ do an exclusive lock to get an order number /
$id = fread($fp,filesize("
order_id.txt"));
$id++;
echo "<br>Got the lock, id is now $id";
ftruncate($fp, 0); / truncate file /
rewind($fp); / reset pointer /
fwrite($fp, $id); / write new order id /
flock($fp, LOCK_UN); / release the lock /
} else {
echo "Couldn't get the lock!";
}

However, if I put this code inside a session, it fails:

session_start();
echo "<br>Flock Test with Session<br>";
$fp = fopen("order_id.txt", "r+");
if (flock($fp, LOCK_EX)) {
/ do an exclusive lock to get an order number /
$id = fread($fp,filesize("
order_id.txt"));
$id++;
echo "<br>Got the lock, id is now $id";
ftruncate($fp, 0); / truncate file /
rewind($fp); / reset pointer /
fwrite($fp, $id); / write new order id /
flock($fp, LOCK_UN); / release the lock /
} else {
echo "Couldn't get the lock!";
}
session_destroy();

    a month later
    Write a Reply...