This article describes how to use PHP to lock and unlock files, for more information, see. sometimes your php script may require thread security, such as file write operations. This article provides file lock functions and examples. The file lock function can also be used to obtain exclusive processing space to prevent synchronization errors during script execution.
The code is as follows:
<? Php
/*************************************** **********************************
* File lock
* @ Author Zeal Li
* Http://www.zeali.net/
*
**************************************** *********************************/
/*
* Lock_thisfile: obtains the exclusive lock.
* @ Param $ tmpFileStr is used as the file name of the shared lock file (you can create a name as needed)
* @ Param $ locktype: lock type. the default value is false (non-blocking type, that is, if the lock fails, false is directly returned). if it is set to true, the system will wait until the lock is successful before returning the lock.
* @ Return if the lock is successful, the lock instance is returned (this parameter is required when the unlock_thisfile method is used). If the lock fails, false is returned.
*/
Function lock_thisfile ($ tmpFileStr, $ locktype = false ){
If ($ locktype = false)
$ Locktype = LOCK_EX | LOCK_NB;
$ Can_write = 0;
$ Lockfp = @ fopen ($ tmpFileStr. ". lock", "w ");
If ($ lockfp ){
$ Can_write = @ flock ($ lockfp, $ locktype );
}
If ($ can_write ){
Return $ lockfp;
}
Else {
If ($ lockfp ){
@ Fclose ($ lockfp );
@ Unlink ($ tmpFileStr. ". lock ");
}
Return false;
}
}
/**
* Unlock_thisfile: Unlock the previously obtained lock instance
* @ Param $ fp lock_thisfile return value
* @ Param $ tmpFileStr is used as the file name of the shared lock file (you can create a name as needed)
*/
Function unlock_thisfile ($ fp, $ tmpFileStr ){
@ Flock ($ fp, LOCK_UN );
@ Fclose ($ fp );
@ Fclose ($ fp );
@ Unlink ($ tmpFileStr. ". lock ");
}
?>
The code is as follows:
<? Php
// Example
$ TmpFileStr = "/tmp/mylock. loc ";
// Wait for the operation permission to be obtained. if you want to return immediately, set the second parameter to false.
$ Lockhandle = lock_thisfile ($ tmpFileStr, true );
If ($ lockhandle ){
// Perform all the transactions that require exclusive processing.
//......
// The transaction has been processed.
Unlock_thisfile ($ lockhandle, $ tmpFileStr );
}
?>