PHP Lock file while reading - flock() makes my file blank

212 views Asked by At

As you can see in the code below, I'm trying to use flock to prevent other clients to acess the php (actually multiple users will acess this something like 10 times per second, each one), as I've found searching here... But this is not working. My data.txt is getting blank everytime doing this.

<?php
$fileName = $_GET["room"]."/data.txt";

function replaceLine($data){
    if (stristr($data, $_GET["player"])){
        return $_GET["player"]." ".$_GET["data"]."\n";
    } 
    return $data;
}

$file = fopen($fileName,"r");

if (flock($file, LOCK_EX)){
    //ftruncate($file, 0);
    ///--------------

    $data = file($fileName);
    $data = array_map("replaceLine", $data);
    file_put_contents($fileName, implode('', $data));

    echo fread($file, filesize($fileName)+1);

    ///--------------
    fflush($file);
    flock($file, LOCK_UN);
} else {
    echo "wait";
}

fclose($file);

?>

This is the original code (that I was trying to modify to prevent making the file empty): (It works as I want, but have this file problem...)

<?php
$fileName = $_GET["room"]."/data.txt";

function replaceLine($data){
    if (stristr($data, $_GET["player"])){
        return $_GET["player"]." ".$_GET["data"]."\n";
    } 
    return $data;
}

$data = file($fileName);
$data = array_map("replaceLine", $data);
file_put_contents($fileName, implode('', $data));

$file = fopen($fileName,"r");
echo fread($file, filesize($fileName)+1);
fclose($file);

?>

Sorry for asking this newbie question, but I have not idea how to fix this and I'm searching and trying different things for weeks! Thanks!

1

There are 1 answers

0
i-man On BEST ANSWER

You are opening the file for read only and then you are attempting to write to that same file. Try setting the fopen parameter to read/write.

 $file = fopen($fileName,"r+");

I would also use fwrite() instead of file_put_contents() since you already have the file pointer and opening it again will likely be denied by the lock.