PHP block file from reading - php

I am trying a simple algorithm which says:
File1: (lock.php)
Open a File
Lock the File, so that no other PHP file can read this
Sleep
Release Lock
File2: (lockstatus.php)
Try to open the file.
If not opening
Wait for Lock to release
Else
Read the file
My code implementation:
Lock.php:
<?php
$f = fopen("key",'a');
if (flock($f, LOCK_EX | LOCK_NB)) {
echo "File Locked. For Next 60 Seconds\n";
sleep(60);
var_dump(flock($f, LOCK_UN)); //release lock
echo "lock released";
} else {
echo "blocked";
}
?>
Lockstatus.php
<?php
do {
echo "\n";
$f = fopen("key",'a');
if ($f) {
echo "Readable\n";
fclose ($f);
} else {
echo "Blocked! I am waiting\n";
sleep(10);
}
} while (!$f); //wait until fopen does not work
?>
Problem:
Even, flock is applied, the Lockstatus.php is able to open the file.
Question:
How to block the file reading at Lockstatus.php once it is locked by Lock.php?

The problem is that flock() only provides advisory locking. The other program may completely ignore this and proceed to fopen and fread or whatever else. The key is to use flock in your Lockstatus.php as well after your do the fopen to check if there are existing locks. flock in Lockstatus.php would fail and then you would know there is an existing lock.

This function flock() has different behavior on linux and windows.
Take a deep look at "Notes" on PHP docs. This might be your issue.
flock on PHP Docs
After that, pay attention on r+ parameter, it´s mandatory for reading+locking.
$fp = fopen('/tmp/lock.txt', 'r+');
It wont work with a.

Related

PHP flock does not lock second run of the script

I trying to implmente a simpler version of the code in this answer:
How to detect whether a PHP script is already running?
The problem described here is my EXACT situation. I want to prevent cron from launching the same script if it's already running.
I started with this simple test code:
<?php
$script_name = __FILE__;
$lock_file_name = basename($script_name, ".php") . ".lock";
$fp = fopen($lock_file_name, "c");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
//ftruncate($fp, 0); // truncate file
//fwrite($fp, "Write something here\n");
//fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
echo "GOT LOCK\n";
sleep(20);
} else {
echo "Couldn't get the lock!\n";
}
flock($fp, LOCK_UN); // release the lock
fclose($fp);
?>
As I understand it, I launch this code in one console and read the Got Lock. If I launch it in another console the I should get the Coudn't get the lock message. Howver I get the Got Lock message both times.
What am I doing wrong?
The file is only locked for the duration of the script. Once the PHP finishes its activities the script tereminates and then the OS unlocks the file.
Note that your sleep(20) call is coming after you have unlocked the file, so there is no pause when the file is locked. So it sounds like you're in effect calling the single script twice in sequence rather than in parallel.
Solution:
Move the sleep(20) statement to before the lock is removed (actually you unlock twice so simply removing the first unlock does this).
$fp = fopen($lock_file_name, "c");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
echo "GOT LOCK\n";
/** this time window allows you to run another parallel script to prove the locking mechanism works **/
sleep(20);
} else {
echo "Couldn't get the lock!\n";
}
flock($fp, LOCK_UN); // release the lock
fclose($fp);

PHP script file loads indefinitely on browser when flock (LOCK_SH/LOCK_EX)

I came across this link while trying to learn how to lock files to prevent a script reading from a file as another is writing, or two scripts writing to the same file simultaneously.
I created two scripts, readandwritelock.php and readlock.php, the first script to retrieve the file with file_get_contents, append it and then write back to the same file with file_put_contents($file, $data, LOCK_EX), and the second that just retrieves the file with file_get_contents after flock($file, LOCK_SH).
<?php
//readandwritelock.php
$myfile = fopen('15-11-2018.txt', 'r+');
if (flock($myfile, LOCK_SH)) {
echo "Gotten lock<br>";
$current = file_get_contents('15-11-2018.txt');
/*I commented this on my second test to see if file_put_contents will work.
After uncommenting and third test, it does not work anymore.
if (flock($myfile, LOCK_UN)) {
echo "Unlocked<br>";
}*/
$current .= "appending";
if (file_put_contents('15-11-2018.txt', $current, LOCK_EX)) {
echo "Success";
}
else {
echo "Failed";
//browser loads indefinitely so this does not run
}
fclose($myfile);
}
?>
The problem I am facing is that the first try I was able to file_get_contents after getting the lock, and then releasing the lock and proceed to append and file_put_contents($file, $data, LOCK_EX). However on the second try I decided to comment the releasing of the LOCK_SH lock to test and see what would happen. The script file loads indefinitely (Waiting for localhost...) on my browser, so I reverted back the changes for my third try, but this time the script file still loads indefinitely. It's as if the LOCK_SH was never released.
I must be doing something wrong, but I do not know what exactly it is. Could someone explain?
This was tested on XAMPP and macOS High Sierra and Chrome.
<?php
//readlock.php
//works as normal
$myfile = fopen('15-11-2018.txt', 'r');
if (flock($myfile, LOCK_SH)) {
echo "Gotten lock<br>";
$current = file_get_contents('15-11-2018.txt');
echo $current;
if (flock($myfile, LOCK_UN)) {
echo "<br>Unlocked";
}
fclose($myfile);
}
?>
The reason why your browser seems to load indefinitely is because your PHP file never finishes.
First you get a LOCK_SH (a shared or read lock) for your file, which is fine while you are reading the content.
The problem is that you also try to get a LOCK_EX (an exclusive lock) on the same file in the file_put_contents function. Therefore the file_put_contents functions blocks until all other locks (shared AND exclusive ones) are unlocked, which can't work (this is a deadlock).
For your code to work properly, you can either try to get an exlusive lock in the first place
if( flock($myfile, LOCK_EX) ) {
// ...
or you unlock the shared lock before you write
flock($myfile, LOCK_UN);
if ( file_put_contents('15-11-2018.txt', $current, LOCK_EX) ) {
// ...
In general it is a good idea to keep a locks life as short as possible. If you plan to make extensive manipulations to your data between reading and writing, I would recommend to unlock the file right after reading and lock it again right for writing.

with php fopen() flock() file() Why does it work like this

so
if i fopen one file with a+ like
fopen($filepath,'a+');
file($filepath);
and then i use file($filepath) get the file contents it's ok
but why i when
i locked the file with flock i also can use file() function get the content
why ?
$fp = fopen($filepath, "a+");
while (1) {
$f =flock($fp,LOCK_EX);
if($f){
fwrite($fp,'abc');
echo "ok loked \n";
sleep(1);
$te =file($filepath);
if(strlen($te[0])==10){
echo "this is cont ".$te[0]."\n";
echo "ok this the end \n";
ftruncate($fp,0);
fflush($fp);
}
flock($fp, LOCK_UN);
break;
}
}
fclose($fp);
what about they relation?
when flock file the file()function is use the fopen resource?
file is independent function or use fopen?
fopen and file are two different functions.
fopen The fopen function does something entirely different—it opens a file
descriptor, which functions as a stream to read or write the file. It
is a much lower-level function, a simple wrapper around the C fopen
function, and simply calling fopen won't do anything but open a
stream.
file — Reads entire file into an array
flock is per process. So if the same process (including all threads) attempts flock multiple times it will always succeed.
Read the warnings at the end of the documentation:
https://www.php.net/manual/en/function.flock.php

Does PHP offer file concurrency in this scenario?

I have a cache file that is updated every hour or so. The file size ranges from 100KB to 1MB. The way the cache is updated is with the file_put_contents() method.
Only the server writes to the file. However, there is continuous access to the file. The file is accessed by users by a script that performs a one time read through readfile() to echo it to the user.
If the file is being read by the caching script, and the server runs the user reading script, or the other way around, would there be a problem? Or is this handled automatically by PHP>
Basically, you should lock the file while writing or reading. At least, it guarantees that there is no problem. It is the way of good programming!. The example is shown below.
<?php
$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
fwrite($fp, "Write something here\n");
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
?>
More information

php script will only run one at a time

I have a script that I want to make sure only one is running, I am doing:
$fp = fopen("lock.txt", "w");
if (flock($fp, LOCK_EX|LOCK_NB)) { // do an exclusive lock
//Processing code
flock($fp, LOCK_UN);
}else{
echo "Could not lock file!";
}
fclose($fp);
The problem is when I start the second script, it just stays there waiting. If I then stop the first script, the second script will then print "Could Not lock this file". Why doesn't the second script just stop immediately and report that message?
If it ran the second script, it would know that the file is locked and should exit. When I watch my processes I can see the second script sat there ... it's just wating.
Thanks.
EDIT: I have just tried a quick and dirty database lock i.e set a running field to -1 and check for it when the script opens. But that doesn't work. I have also tried using sockets as described: here . It seems like the second file won't even run ... Should I even be worried?
$fp = fopen("lock.txt", "w");
$block = 0;
if (flock($fp, LOCK_EX|LOCK_NB, $block)) { // do an exclusive lock
sleep(5);
flock($fp, LOCK_UN);
echo "Could lock file!";
}else{
echo "Could not lock file!";
}
fclose($fp);
works for me. Try adding the 3'rd parameter
Edit:
You may have some session locking problems:
when you call session_start() it will block(put further requests in a waiting state) any other requests to your script until the original script that started the session has finished. To test this, try either accessing with 2 different browsers, or avoid calling session_start() in this script.

Categories