file_get_contents with empty file not working PHP
Asked Answered
H

1

5

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 ?

Headreach answered 12/7, 2013 at 12:32 Comment(0)
D
17

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.

Dover answered 12/7, 2013 at 12:36 Comment(3)
you say file_get_contents return an empty string like a false. So this line file_get_contents($filename) !== false is supposed to be false, because file_get_contents return false. So why it's work and not echo "fail"?Headreach
It has to do with the types of the variables. file_get_contents returns false (a boolean) if it can't open the file, it returns '' (a string) if it opens an empty file. The triple character comparison (!==) also checks if the types of the variables are the same. Please check the link to the documentation in my answer for more information.Dover
Ok, I did not grasp the nuance between "type" and "equal to". Thank you for your explanations.Headreach

© 2022 - 2024 — McMap. All rights reserved.