How to lock files under PHP

Source: Internet
Author: User
Tags flock

<?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);
}

?>



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.