I am doing an account 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 whenever the app is viewed by another user. The code is in my AppController
and afterFilter
. Whenever you test the file is updated clean the cache data, for the session to cease to exist. What is the problem with the code?
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);
}