用于使用 PHP 写入文件的文本框


Textbox to write to a file with PHP

我正在尝试将数据写入文件,是 0 还是 1 取决于用户输入文本框的值,如果用户写入"On",则应将值 1 写入文件,如果用户输入"Off",则应将值 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);
    }
    ?>

问题出在$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');
    }