1

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.