PHP file Lock Write instance parsing.
Original address: http://www.jbxue.com/article/23118.html
PHP file Write method to deal with multi-threaded writing, the specific code:
functionFile_write ($file _name,$text,$mode= ' A ',$timeout=30){ $handle=fopen($file _name,$mode); while($timeout>0){ if(Flock($handle, LOCK_EX)) {//exclusive locking of the sex$timeout--; Sleep(1); } } if($timeout> 0 ){ fwrite($handle,$text.‘ \ n '); Flock($handle,Lock_un); fclose($handle);//Release lock Actionreturn true; } return false; }
where the flock (int $handle, int $operation) function operation handle must be a file pointer that has already been opened.
Operation can be one of the following values:
To get a shared lock (read program), set operation to Lock_sh (the previous version of PHP 4.0.1 is set to 1).
To obtain an exclusive lock (written program), set operation to LOCK_EX (2 in previous versions of PHP 4.0.1).
To release the lock (either share or exclusive), set operation to Lock_un (3 in previous versions of PHP 4.0.1).
If you do not want flock () to block when locked, Operation plus LOCK_NB (set to 4 in previous versions of PHP 4.0.1).
In addition, fclose () is used to release the lock operation, which is called when the code finishes executing.
Articles you may be interested in:
- PHP Flock File Lock Usage Example tutorial
- PHP in flock file lock detailed