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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号