I’m fairly new to PHP, but have managed to set up a script that simply displays the amount of times a button is clicked each time a user clicks on it.
Here is the PHP:
<?php
$f = fopen('counter.txt', 'r+');
flock($f, LOCK_EX);
$total = (int) fread($f, max(1, filesize('counter.txt')));
if (isset($_POST['submit'])) {
rewind($f);
fwrite($f, ++$total);
}
fclose($f);
?>
Here is the HTML:
<form action='' method="post">
<input type="submit" name="submit" value="click" />
</form>
This button has been clicked <?php echo $total; ?> times.
The counter works and everything, but there are three issues I hope you guys can help me with:
-
The counter increases each time the page is reloaded. I only want the counter to increase when the button is clicked. Is there a way I can fix this?
-
Each time I refresh the page, Firefox asks me to confirm that I want the page to be reloaded. I know there is an option in my browser settings to prevent this, but was wondering if there was a way to refine my php so that this message does not occur for the user as well.
-
If you click the button a couple of times and then try to use the Back button, it takes you through each one of the previous clicks. Again, is there a way to fix my code so that it does not do this and instead goes to the previous page?
HUGE thanks!!
In order:
It increases the counter when a POST request is made; the problem is that your script doesn’t do redirection after the POST has been processed. Just a simple
header()redirect will do. This turns the next request in a GET and voila!Again, when you click the button once it will refresh the page and post your form; because your script doesn’t redirect, when you reload the page Firefox (and other browsers too) will ask you for confirmation.
The back button behaviour can’t really be changed, but you could force the browser to never cache the page (search for ‘disabling browser cache php’ to see what headers you have to provide).