Search code examples
phpfileurl-rewriting

PHP, check if the file is being written to/updated by PHP script?


I have a script that re-writes a file every few hours. This file is inserted into end users html, via php include.

How can I check if my script, at this exact moment, is working (e.g. re-writing) the file when it is being called to user for display? Is it even an issue, in terms of what will happen if they access the file at the same time, what are the odds and will the user just have to wait untill the script is finished its work?

Thanks in advance!

More on the subject...

Is this a way forward using file_put_contents and LOCK_EX?

when script saves its data every now and then

file_put_contents($content,"text", LOCK_EX);

and when user opens the page

if (file_exists("text")) {

function include_file() {

    $file = fopen("text", "r");
    if (flock($file, LOCK_EX)) {
    include_file();
    }
    else {
    echo file_get_contents("text");
    }
}
 } else {
echo 'no such file';
}

Could anyone advice me on the syntax, is this a proper way to call include_file() after condition and how can I limit a number of such calls?

I guess this solution is also good, except same call to include_file(), would it even work?

function include_file() {

$time = time();
$file = filectime("text");

if ($file + 1 < $time) {
echo "good to read";
} else {
echo "have to wait";
include_file();
}

}

Solution

  • To check if the file is currently being written, you can use filectime() function to get the actual time the file is being written.

    You can get current timestamp on top of your script in a variable and whenever you need to access the file, you can compare the current timestamp with the filectime() of that file, if file creation time is latest then the scenario occured when you have to wait for that file to be written and you can log that in database or another file.

    To prevent this scenario from happening, you can change the script which is writing the file so that, it first creates temporary file and once it's done you just replace (move or rename) the temporary file with original file, this action would require very less time compared to file writing and make the scenario occurrence very rare possibility.

    Even if read and replace operation occurs simultaneously, the time the read script has to wait will be very less.