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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With