我正在尝试将数据写入文件,无论0或1是否取决于用户输入文本框的值,如果用户写入“On”值1应该写入文件,如果用户输入'关',值0应写入该值。如果用户输入任何其他文本,文件值应具有前一个值而没有任何更改,这是我的代码,一切正常,除了用户输入无效值的最后一部分,文件变为空,没有值0和1请帮忙
<?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);
}
?>
答案 0 :(得分:0)
问题出在$fh = fopen($myFile, 'w') or die("can't open file");
这一行。当您输入错误的值时,此行将清空您的文件。您只能在使用输入写入值
$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');
}