<?php
/**********************************************
*file Lock
* @author Zeal Li
*http://www.zeali.net/
***********************************************/
/*
*lock_thisfile: Get exclusive lock
* @param $tmpFileStr file name used as a shared lock file (you can name one)
* @param $locktype lock type, the default is False (Non-blocking, that is, if the lock fails to return false directly), set to True will wait for lock success to return
* @return If the lock succeeds, return the lock instance (which is required when using the Unlock_thisfile method) and return False if the lock fails.
*/
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: Unlocking a previously acquired lock instance
* @param $fp The return value of the Lock_thisfile method
* @param $tmpFileStr file name used as a shared lock file (you can name one)
*/
function Unlock_thisfile ($fp, $tmpFileStr) {
@flock ($fp, Lock_un);
@fclose ($FP);
@fclose ($FP);
@unlink ($tmpFileStr. " Lock ");
}
?>
<?php
Use examples
$TMPFILESTR = "/tmp/mylock.loc";
Wait for permission to operate, and set the second argument to False if you want to return immediately.
$lockhandle = Lock_thisfile ($tmpFileStr, true);
if ($lockhandle) {
All transactions that need to be exclusive are done here.
// ... ...
The transaction has finished processing.
Unlock_thisfile ($lockhandle, $TMPFILESTR);
}
?>