note 24908 added to function.flock

From: Date: Wed, 04 Sep 2002 16:58:46 +0000
Subject: note 24908 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-36115@lists.php.net to get a copy of this message
Warning! When PHP is running as a CGI or fast-CGI extension in Apache, flock() does not guarantee that your file updates will complete!!! If a browser starts a request and interrupts it fast enough by using many F5-key refreshes, Apache will KILL the PHP process in the middle of the update operation (because it will detect an unexpected socket close before the PHP script is complete), leaving an incomplete or truncated file! A simple PHP script that increments a counter in a text file will demonstrate this: to update the counter, one needs to gain a lock then open the counter file in "a+" mode, rewind it, read it, rewind again, ftruncate it befire writing the new value and closing the counter file and the lock file. Have your script display the new counter value. Now use your favorite browser on your script, and make many refreshes from the same PC, using the F5-Refresh key, you'll see that sometimes the counter returns to 0, because there's an interruption after the counter file was truncated but before the new counter value was written to the file! Note that this affects also simple databases updates without rollback logs such as MySQL! Before updating any data, as a security measure, and if you don't have rollback logs, you should strictly limit the number of update requests per seconds a user can make through your PHP script. Shame, this requires a database or logging file to enable tracking user activity. The only solution is to use an auto-backup system (for file-based databases), or a database engine with rollback capability... I don't know if PHP implements a way to handle gracefully kill signals sent by Apache, so that we can ensure that we can complete a critical update operation. For this problem, flock() is not a solution! This is a MAJOR security issue for all sites that use text-file based databases! -- http://www.php.net/manual/en/function.flock.php http://master.php.net/manage/user-notes.php?action=edit+24908 http://master.php.net/manage/user-notes.php?action=delete+24908 http://master.php.net/manage/user-notes.php?action=reject+24908

« previous php.notes (#36115) next »