Home > Backend Development > PHP Tutorial > php警告的原因

php警告的原因

WBOY
Release: 2016-06-06 20:20:47
Original
1454 people have browsed it

<code><form action="index.php" method="post">
    <input type="text" name="user">
    <input type="text" name="password">
    <input type="submit" value="submit">
</form></code>
Copy after login
Copy after login
<code><?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';
    }

?>


</code>
Copy after login
Copy after login

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

回复内容:

<code><form action="index.php" method="post">
    <input type="text" name="user">
    <input type="text" name="password">
    <input type="submit" value="submit">
</form></code>
Copy after login
Copy after login
<code><?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';
    }

?>


</code>
Copy after login
Copy after login

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

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

把 fclose 放在 while 之外

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

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template