C10H15N C10H15N - 3 months ago 16
PHP Question

PHP script that counts button clicks

I have a script that adds +1 or -1 to a variable when a certain button is pressed. The "+1" button works perfectly, but the "-1" one acts odd when the variable has the value of "10" (maybe other values too). Instead of showing "9" when I click the button, it shows "90".

PHP:

<?php
$myfile = fopen("response.txt", "r+") or die("Unable to open file!");
$currentvalue = file_get_contents("response.txt");
$currentvalue = $currentvalue -1;
fwrite($myfile, $currentvalue);
fclose($myfile);
header( 'Location: otherfile.php' ) ;
?>


HTML

<form method="post" action="minus.php">
<button> Remove one </button>
</form>


I know that there are better approaches to this task, but the code above is the best I can come up with, considering my basic knowledge in php.

thanks.

Answer

This happens because you open the file in r+ mode. This doesn't truncate the file, so when you write the "9", you overwrite the "1" that was there from the "10", while the second character in that file is still the "0". This gives you "90".

Solve this by not using fopen, fwrite or fclose: remove those statements. Instead write the result with file_put_contents:

$currentvalue = file_get_contents("response.txt");
$currentvalue = $currentvalue - 1;
file_put_contents("response.txt", $currentvalue);