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
andfile_put_contents
PHP if your server allows.– Pedro Henrique