Search code examples
phpfopenfwrite

fwrite do not overwrite my .txt


I have a button, I would like that when I press it, it writes on a text file its state and the button changes its value, like a toggle switch.

<button type="button"><?php echo $button ?></button>

My problem is, once I pressed it, the first value on the text file is not overwritten by the next one. They are both written.

I should have this on the text file: ON or OFF but I get this ONOFF or OFFON.

<?php
$file = fopen('state.txt', 'r+');
$state = fread($file, '3');

if ($state == 'ON') {
    $button = 'OFF';
    fwrite($file, 'OFF');
} elseif ($state == 'OFF') {
    $button = 'ON';
    fwrite($file, 'ON');
} else {
    $button = 'error';
}

fclose($file);
?>

Moreover I want my php and my html code on the same page.

Thank you.


Solution

  • You've opened the file for r/w, then read from it.

    The "pointer" is at the last char; the next write happens where the pointer is and you get the data appended.

    2 options: Close the file after reading it and reopen it to write

    or use fseek($file,0) to move the pointer back to the beginning.