PHP locks and unlocks file locks

Source: Internet
Author: User
Tags flock

In the project, generally use the log, such as database query log, access log, external interface request return parameter log, in the process of writing the log is as follows

$file = ' Log.txt ';
$fp = fopen ($file, ' A + ');
if (!is_writable ($file)) {
    die ("The $file is not writable!");
Fwrite ($fp, ' here ');
Fclose ($FP);

But the wording is flawed, a Web site at the same time is not only one user access, the simultaneous access to multiple users, there will be problems, that is, multiple processes using the same resource, the previous process to write half of the process began to write, so the last generated log is chaotic. In this case, the lock is used, during the file lock, the other process will not modify the file, only when the file unlock, you can operate. Written as follows

$file = ' Log.txt ';
$fp = fopen ($file, ' A + ');
if (!is_writable ($file)) {
    exit ("The $file is not writable!");
Flock ($FP, LOCK_EX);//Lock
fwrite ($fp, ' here ');
Flock ($FP, lock_un);//Unlock
fclose ($fp);

If you want to test examples of other processes that cannot manipulate files during file locking, you can use the demo shown below

log.php
$file = ' log.txt ';
$fp = fopen ($file, ' A + ');
if (!is_writable ($file)) {
    exit ("The $file is not writable!");
Flock ($FP, lock_ex);
Fwrite ($fp, ' here ');
Sleep (a);
Flock ($FP, lock_un);
Fclose ($FP);

test.php
$file = ' lock.txt ';
$fp = fopen ($file, ' a ');
Fwrite ($fp, ' good '); Not to be written during sleep
fclose ($fp);

Or use the following example directly to find out that printing is a null value
//var_dump (file_get_contents ($file) during sleep;


When testing, run log.php first, then run test.php, you will find that during sleep, test.php is performed without effect.


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.