Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents with empty file not working PHP

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 ?

like image 296
mpgn Avatar asked Jul 12 '13 12:07

mpgn


People also ask

How check text file is empty or not in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

What is the difference between file_get_contents () function and file () function?

They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string.

What will the file_get_contents () return?

Return Values ¶ The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.


1 Answers

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.

like image 51
rael_kid Avatar answered Oct 04 '22 23:10

rael_kid