Best way to determine if a file is empty (php)?

Php

Php Problem Overview


I'm including a custom.css file in my template to allow site owners to add their own css rules. However, when I ship the file, its empty and there's no sense loading it if they've not added any rules to it.

What's the best way to determine if its empty?

if ( 0 == filesize( $file_path ) )
{
	// file is empty
}

// OR:

if ( '' == file_get_contents( $file_path ) )
{
	// file is empty
} 

Php Solutions


Solution 1 - Php

file_get_contents() will read the whole file while filesize() uses stat() to determine the file size. Use filesize(), it should consume less disk I/O and much less memory.

Solution 2 - Php

Everybody be carefull when using filesize, cause it's results are cached for better performance. So if you need better precision, it is recommended to use something like:

<?
clearstatcache();
if(filesize($path_to_your_file)) {
    // your file is not empty
}

More info here

Solution 3 - Php

Using filesize() is clearly better. It uses stat() which doesn't have to open the file at all.

file_get_contents() reads the whole file.. imagine what happens if you have a 10GB file.

Solution 4 - Php

filesize() would be more efficient, however, it could be misleading. If someone were to just have comments in there or even just whitespace...it would make the filesize larger. IMO you should instead look for something specific in the file, like /* enabled=true */ on the first line and then use fopen/fread to just read the first line. If it's not there, don't load it.

Solution 5 - Php

As mentioned in other answers, filesize is the way to go for local files. Many stream wrappers on the other hand, including HTTP, do not have stat() support, thus filesize will fail, whereas file_get_contents will work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionScott BView Question on Stackoverflow
Solution 1 - PhpSpliffsterView Answer on Stackoverflow
Solution 2 - PhpuserlondView Answer on Stackoverflow
Solution 3 - PhpThiefMasterView Answer on Stackoverflow
Solution 4 - PhpCrayon ViolentView Answer on Stackoverflow
Solution 5 - PhpNikiCView Answer on Stackoverflow