确定文件是否为空的最佳方法(php)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4857182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to determine if a file is empty (php)?
提问by Scott B
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.
我在我的模板中包含了一个 custom.css 文件,以允许网站所有者添加他们自己的 css 规则。但是,当我发送文件时,它是空的,如果他们没有向其中添加任何规则,则加载它是没有意义的。
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
}
回答by Spliffster
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.
file_get_contents()
将读取整个文件,同时filesize()
用于stat()
确定文件大小。使用filesize()
,它应该消耗更少的磁盘 I/O 和更少的内存。
回答by userlond
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:
大家在使用时要小心filesize
,因为它的结果会被缓存以获得更好的性能。因此,如果您需要更好的精度,建议使用以下内容:
<?
clearstatcache();
if(filesize($path_to_your_file)) {
// your file is not empty
}
回答by ThiefMaster
Using filesize()
is clearly better. It uses stat()
which doesn't have to open the file at all.
使用filesize()
显然更好。它使用stat()
which 根本不必打开文件。
file_get_contents()
reads the whole file.. imagine what happens if you have a 10GB file.
file_get_contents()
读取整个文件......想象一下如果你有一个 10GB 的文件会发生什么。
回答by Crayon Violent
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.
filesize()
会更有效,但是,它可能会产生误导。如果有人只是在那里发表评论,甚至只是空白......它会使文件变大。IMO 你应该在文件中寻找特定的东西,比如/* enabled=true */
在第一行,然后使用 fopen/fread 来读取第一行。如果它不存在,请不要加载它。
回答by NikiC
As mentioned in other answers, filesize
is the way to go for local files. Many stream wrappers on the other hand, including HTTP, do nothave stat()
support, thus filesize
will fail, whereas file_get_contents
will work.
正如其他答案中提到的,filesize
是本地文件的方法。在另一方面,许多流包装,包括HTTP,千万不能有stat()
支持,从而filesize
会失败,而file_get_contents
将工作。