How to lock a file under PHP _php tutorial

Source: Internet
Author: User
/*
*lock_thisfile: Get exclusive lock
* @param $tmpFileStr used as the file name of the shared lock file (can be a name randomly)
* @param $locktype lock type, the default is False (non-blocking, that is, once the lock fails to return false directly), set to True will wait until the lock succeeds to return
* @return If the lock succeeds, the lock instance is returned (this parameter is required when the Unlock_thisfile method is used), and the lock failure returns false.
*/
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 An instance of a previously acquired lock
* @param $fp The return value of the Lock_thisfile method
* @param $tmpFileStr used as the file name of the shared lock file (can be a name randomly)
*/
function Unlock_thisfile ($fp, $tmpFileStr) {
@flock ($fp, Lock_un);
@fclose ($FP);
@fclose ($FP);
@unlink ($tmpFileStr. ". Lock ");
}
?>

Examples of Use
$TMPFILESTR = "/tmp/mylock.loc";

Wait for the operation permission, if you want to return immediately, set the second argument to false.
$lockhandle = Lock_thisfile ($tmpFileStr, true);
if ($lockhandle) {
All transactions that require exclusive processing are performed here.
// ... ...
The transaction has finished processing.
Unlock_thisfile ($lockhandle, $TMPFILESTR);
}

?>

http://www.bkjia.com/PHPjc/629786.html www.bkjia.com true http://www.bkjia.com/PHPjc/629786.html techarticle PHP/* *lock_thisfile: Get exclusive lock * @param $tmpFileStr used as the file name of the shared lock file (can be any name) * @param $locktype lock type, the default is False (non ...)

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.