首页 > php警告的原因

php警告的原因

<form action="index.php" method="post">
    <input type="text" name="user"/>
    <input type="text" name="password"/>
    <input type="submit" value="submit"/>
</form>
<?php
    $user=trim($_POST['user']);
    $password=trim($_POST['password']);

    if(!$user || !$password){
        echo 'please make sure no empty input';
        exit;
    }
    //write to test.txt
    $handle=fopen('test.txt','rb+');
    if($handle){
        while(($buffer=fgets($handle))!==false){
            preg_match('/.*:(.*?)-/',$buffer,$array);
            if($array[1]===$user){
                echo 'user exist';
                exit;
            }
            fwrite($handle,'$user:'.$user.'------'.'$password:'.$password."\r\n");
            fclose($handle);
        }
    }else{
        echo 'fail to open file';
    }

?>


写的这个程序是向txt写入文字。可以实现功能,但会有警告。
Warning: fgets(): 5 is not a valid stream resource in C:\xampp\htdocs\index.php on line 13
这个警告什么意思。怎么消除?


fclose($handle);
把这个放到while外面,你读了一次就关闭了,当然报错了


你这个写法就由问题,
把 fgets 写在 while 条件里,第一次读还是正常,但是正常读了之后你在 while 里把 $handle 就 close 了,那循环之后再次判断 while 的时候 fgets 读一个已经关闭的文件资源 当然就报这个警告了……

把 fclose 放在 while 之外

【热门文章】
【热门文章】