Home > other >  How to lock a file, read content and overwrite (truncate) it
How to lock a file, read content and overwrite (truncate) it

Time:10-11

When I use option w it truncates the file before reading it. I want to lock the file which is used by multiple scripts, then read and overwrite, then unlock. This is the simplified code.

$fp = fopen($file, "w ");
if(flock($fp, LOCK_EX)) {
    $content = fread($fp, $filesize);
    echo $content; // this is empty, must not be empty
    $job_queue = explode("\n", $content, LOCK_EX);
    $next_job = array_shift($job_queue);
    fwrite($fp, implode("\n", $job_queue));
    flock($fp, LOCK_UN);
} else {
    echo '<br>Error: cannot lock job queue file';
}
fclose($fp);

CodePudding user response:

r = read mode only
r  = read/write mode
w = write mode only
w  = read/write mode, if the file already exists override it (empty it)

do "r " instead and truncate with PHP's ftruncate()

CodePudding user response:

To solve it, added manually a truncate to 0 (beginning of file) and changed open option to a

$fp = fopen($file, "a ");
if(flock($fp, LOCK_EX)) {
    $content = fread($fp, $filesize);
    echo $content; // this is not empty now
    $job_queue = explode("\n", $content, LOCK_EX);
    $next_job = array_shift($job_queue);
    ftruncate($fp, 0);
    fwrite($fp, implode("\n", $job_queue));
    flock($fp, LOCK_UN);
} else {
    echo '<br>Error: cannot lock job queue file';
}
fclose($fp);
  • Related