Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a text file is empty in PHP?

Tags:

file

php

How to check if a text file is empty in PHP?

I've tried what I found on the internet which is this:

if( '' != filesize('data.txt')){

    echo "The file is empty";
}

ALSO THIS:

if( 0 != filesize('data.txt')){

    echo "The file is empty";
}

And no of them seems to work.

like image 948
Montoolivo Avatar asked Nov 30 '22 00:11

Montoolivo


2 Answers

Simply use this first:

if (filesize('data.txt') == 0){
    echo "The file is DEFINITELY empty";
}

if still in doubt (depending what empty meaning to you), also try:

if (trim(file_get_contents('data.txt')) == false) {
    echo "The file is empty too";
}

Take a note on Niels Keurentjes, becareful as http://php.net/manual/en/function.empty.php said:

Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

like image 183
daribs Avatar answered Dec 01 '22 14:12

daribs


It should be this. You check if the filesize is 0. You're code asked if the filesize was different of 0 and then it was empty.

if ( 0 == filesize( $file_path ) )
{
    // file is empty
}
like image 21
TeeDeJee Avatar answered Dec 01 '22 13:12

TeeDeJee