PHP does not update file data . txt

Asked

Viewed 87 times

4

I am running a visualization counter for an application, which is stored in a .txt. file, however, the file is always 0. If the file does not exist, it is created, with the value 0 written. However this is never updated every time the app is viewed by another user. The code is found in my AppController in the afterFilter. Every time I test whether the file is updated clean the cache data, the session ceases to exist. What’s the problem with the source?

Code

    public function afterFilter(){
    $counter = APP."webroot/counter/counter.txt";

 // verifica se o ficheiro existe. se não existe cria um com o valor 0.
    if (!file_exists($counter)) {
        $f = fopen($counter, "w") or die("o ficheiro não pode ser aberto");
        fwrite($f,"0");
        fclose($f);
    }

 // lê o valor do ficheiro
    $f = fopen($counter,"r") or die("o ficheiro não pode ser aberto");;
    $counterVal = fread($f, filesize($counter));
    fclose($f);

 //verifica se o visitante foi contado, actualiza o ficheiro.
    if(!isset($_SESSION['hasVisited'])){
        $_SESSION['hasVisited']="yes";
        $counterVal++;
        $f = fopen($counter, "w") or die("o ficheiro não pode ser aberto");;
        fwrite($f, $counterVal);
        fclose($f);
    }
    $counterVal = str_pad($counterVal, 5, "0", STR_PAD_LEFT);

}
  • You can try to use file_get_content and file_put_contents PHP if your server allows.

1 answer

2


Your code worked correctly here in my tests...

session_name("TESTESPHP-CotadorVisitas");
session_start();

$counter = __DIR__."/counter.txt";

// verifica se o ficheiro existe. se não existe cria um com o valor 0.
if (!file_exists($counter)) {
    $f = fopen($counter, "w") or die("o ficheiro não pode ser aberto");
    fwrite($f,"0");
    fclose($f);
}

// lê o valor do ficheiro
$f = fopen($counter,"r") or die("o ficheiro não pode ser aberto");;
$counterVal = fread($f, filesize($counter));
fclose($f);

//verifica se o visitante foi contado, actualiza o ficheiro.
if(!isset($_SESSION['hasVisited'])){
    $_SESSION['hasVisited']="yes";
    $counterVal++;
    $f = fopen($counter, "w") or die("o ficheiro não pode ser aberto");;
    fwrite($f, $counterVal);
    fclose($f);
}
$counterVal = str_pad($counterVal, 5, "0", STR_PAD_LEFT);

echo $counterVal;

the error in your may be the lack of a / in:

   $counter = APP."/webroot/counter/counter.txt";
  • Strange you didn’t get any warning about that. Previously I had some problems turning on the file but I stopped receiving warnings after putting it as it is in my question. Thank you so much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.