I have a single webpage and i would like to track how many times it's visited without using a database.
I thought about XML, updating a file every time a user visits the page:
<?xml version='1.0' encoding='utf-8'?>
<counter>8</counter>
Then i thought it could have been a better idea to declare a PHP counter in a separate file and then update it everytime a user visits the page.
counter.php
<?php
$counter = 0;
?>
update_counter.php:
<?php
include "counter.php";
$counter += 1;
$var = "<?php\n\t\$counter = $counter;\n?>";
file_put_contents('counter.php', $var);
?>
With this, everytime update_counter.php
is visited, the variable in the counter.php
file is incremented.
Anyway, i noticed that if the counter.php
file has $counter = 5
and the update_counter.php
file is visited by i.e. 1000 users at the exact same time, the file gets read 1000 times at the same time (so the the value 5
gets read in all requests) the counter.php
file will be updated with value 5+1 (=6)
instead of 1005
.
Is there a way to make it work without using database?
You can use flock()
which will lock the file so that other processes are not writing to the file.
Edit: updated to use fread()
instead of include()
$fp = fopen("counter.txt", "r+");
while(!flock($fp, LOCK_EX)) { // acquire an exclusive lock
// waiting to lock the file
}
$counter = intval(fread($fp, filesize("counter.txt")));
$counter++;
ftruncate($fp, 0); // truncate file
fwrite($fp, $counter); // set your data
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
fclose($fp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With