I have this code in PHP writing views to a text-file and just increasing the number. My question is here: What happens if two or more people are using my site and running the PHP script? Will the server handle it? Will the increasement be saved to the file?
Here is my code (if it helps):
<?php
$clicks = file_get_contents("clicks.txt");
$clicks++;
$fp = fopen("clicks.txt", "w+");
fwrite($fp, $clicks);
fclose($fp);
//give the count to the user
echo "result: $clicks";
?>
First of all: This is not the way I would write a click counter.
That said, 100 users hitting your server at the same time (with initial clicks at 0) might result in a recorded number of 1..100 with low (=wrong) values being prominent.
EDIT: Implementations
I created the below implementations for a file counter in a text file, SQLite and MySQL
Please do not flame me for using the
mysql_*()function family – as allways the code is meant to be instructive, not productive: instructive in the sense of concentrating on the issue at hand, not the surrounding layers.counter-file.php:
counter-sqlite.php:
counter-mysql.php:
As for the performance: I stand corrected. The SQLite implementation is 100 times slower than the two others – this is because I had to accept, that nothing else than
START EXCLUSIVE TRANSACTIONwould end a test ofab -n 1000 -c 50 http://127.0.0.1/stackoverflow/counter/counter-sqlite.phpwith 1000 clicks counted.My recommendation for the OP is to use the MySQL version – it is fast and will reliably save the counter over an OS crash. The file version has nearly the same performance characteristics, but it can quite easily be destroyed by an OS crash.