douwen3127 2016-02-01 08:06
浏览 251
已采纳

使用PHP写入文件的文本框

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);
    }
    ?>
  • 写回答

1条回答 默认 最新

  • douchiwan1503 2016-02-01 08:18
    关注

    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');
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容