I'm trying to write data to a file, whether 0 or 1 depends on the value the user enter to a text box, if the user write 'On' value 1 should be written to the file, if the user enter 'Off', value 0 should be written to the value. if the user enter any other text the file value should have the previous value without any change, this is my code, everything work fine except for the last part when the user enter unvalid value, the file become empty with no values no 0 nor 1. please help
<?php
if(isset($_POST['username'])) { //only do file operations when appropriate
$state;
$a = $_POST['username'];
$myFile = "ledstatus.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
if($a == "On"){
$state = '1';
fwrite($fh,$state);
fclose($fh);
//print("LED on");
}
elseif($a == "Off"){
$state = '0';
fwrite($fh,$state );
fclose($fh);
//print("LED off");
}
else{
die('no post data to process');
}
}
else {
$fh = fopen("ledstatus.txt", 'r');
$a = fread($fh, 1);
fclose($fh);
}
?>
The problem is with $fh = fopen($myFile, 'w') or die("can't open file");
this line. When you enter wrong value this line empty your file.You only open the file when use enter write value as
$a = $_POST['username'];
$myFile = "ledstatus.txt";
if ($a == "On") {
$fh = fopen($myFile, 'w') or die("can't open file");
$state = '1';
fwrite($fh, $state);
fclose($fh);
//print("LED on");
} elseif ($a == "Off") {
$fh = fopen($myFile, 'w') or die("can't open file");
$state = '0';
fwrite($fh, $state);
fclose($fh);
//print("LED off");
} else {
print_r('error');
}