Home > Backend Development > PHP Tutorial > How to lock files under PHP_PHP Tutorial

How to lock files under PHP_PHP Tutorial

WBOY
Release: 2016-07-13 17:08:52
Original
1169 people have browsed it

/*
*lock_thisfile: Obtain exclusive lock
*@param $tmpFileStr The file name used as the shared lock file (you can give it any name)
*@param $locktype lock type, the default is false (non-blocking, that is, once the lock fails, it will directly return false). If set to true, it will wait for the lock to be successful before returning
*@return If the lock is successful, the lock instance is returned (this parameter is required when using the unlock_thisfile method), 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 The return value of the lock_thisfile method
*@param $tmpFileStr The file name used as the shared lock file (you can give it any name)
*/
function unlock_thisfile($fp,$tmpFileStr){
@flock($fp,LOCK_UN);
@fclose($fp);
@fclose($fp);
@unlink($tmpFileStr.".lock");
}
?>

// Usage 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){
// All transaction processing that needs to be exclusive is done here.
// ... ...
// Transaction completed.
unlock_thisfile($lockhandle,$tmpFileStr);
}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629786.htmlTechArticle?php /* *lock_thisfile: Obtain exclusive lock*@param $tmpFileStr The file used as the shared lock file Name (you can give it any name) *@param $locktype lock type, the default is false (not...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template