file_get_contents with empty file not working PHP

僤鯓⒐⒋嵵緔 提交于 2020-01-02 04:47:09

问题


I try to use file_get_contents form PHP but it's not working.

There is my code :

$filename = "/opt/gemel/test.txt";


if($filecontent = file_get_contents($filename)){

    $nom = fgets(STDIN);

    file_put_contents($filename, $nom, FILE_APPEND);
}
else
    echo "fail";

And my file test.txt is empty. (0 octets). He exists but he is empty.

When i write something into it, my code works perfectly but if he is empty my code echo "fails"

Why that, why he can't open the file text.txt ?


回答1:


The function file_get_contents returns the string that's in the file. If the file contains no data, then file_get_contents returns an empty string. If you would try to var_dump('' == false); you would get true. So, even though the file can be read, the contents of the file evaluates to false.

If you would use this line, your code should work:

if($filecontent = file_get_contents($filename) !== false){

Edit; link to the documentation of the Comparison operators.



来源:https://stackoverflow.com/questions/17615003/file-get-contents-with-empty-file-not-working-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!