使用PHP写入文件的文本框
我正在尝试将数据写入文件,是0还是1取决于用户在文本框中输入的值,如果用户写入“on”值,则应将值1写入文件,如果用户输入“Off”,则应将值0写入该值。如果用户输入任何其他文本,则文件值应具有以前的值而不进行任何更改,这是我的代码,除用户输入未验证值的最后一部分外,一切正常,文件变为空,没有值0或1。请帮忙使用PHP写入文件的文本框,php,Php,我正在尝试将数据写入文件,是0还是1取决于用户在文本框中输入的值,如果用户写入“on”值,则应将值1写入文件,如果用户输入“Off”,则应将值0写入该值。如果用户输入任何其他文本,则文件值应具有以前的值而不进行任何更改,这是我的代码,除用户输入未验证值的最后一部分外,一切正常,文件变为空,没有值0或1。请帮忙 <?php if(isset($_POST['username'])) { //only do file operations when appropriate
<?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);
}
?>
问题在于,$fh=fopen($myFile,'w')或die(“无法打开文件”)代码>这行。当您输入错误的值时,此行将清空您的文件。您仅在使用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');
}
问题在于,$fh=fopen($myFile,'w')或die(“无法打开文件”)代码>这行。当您输入错误的值时,此行将清空您的文件。您仅在使用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');
}
您可以放置另一个else
并将0置于$state
否如果用户输入错误的值,我不希望文件更改其值如果用户输入错误的值,您想要的是什么?显示“错误”,但当我写入打印(“错误”);文件的值变为空,我不希望发生这种情况意味着你不想清空文件,当用户输入错误时,它仍然是最后一个值!!!您可以放置另一个else
并将0置于$state
否如果用户输入错误的值,我不希望文件更改其值如果用户输入错误的值,您想要的是什么?显示“错误”,但当我写入打印(“错误”);文件的值变为空,我不希望发生这种情况意味着你不想清空文件,当用户输入错误时,它仍然是最后一个值!!!