Home  >  Article  >  Backend Development  >  PHP 获取文件大小,求解惑

PHP 获取文件大小,求解惑

WBOY
WBOYOriginal
2016-06-06 20:52:20997browse

假设,我有一个文件: file.zip

// 用 filesize 获取文件大小
$filename = 'file.zip';
echo filesize($filename);

// 文件已经在内存中,用 strlen 计算长度
$content = file_get_contents($filename);
echo strlen($content);

疑惑的地方是:
我用 strlen 计算已经读到内存中的文件的长度 是否 和用 filesize 获取文件长度 必定 相同?

我现在试了几个文件都是相同的,但是,不敢确定是否一定会是相同的。

求肯定的答案!!!

回复内容:

假设,我有一个文件: file.zip

// 用 filesize 获取文件大小
$filename = 'file.zip';
echo filesize($filename);

// 文件已经在内存中,用 strlen 计算长度
$content = file_get_contents($filename);
echo strlen($content);

疑惑的地方是:
我用 strlen 计算已经读到内存中的文件的长度 是否 和用 filesize 获取文件长度 必定 相同?

我现在试了几个文件都是相同的,但是,不敢确定是否一定会是相同的。

求肯定的答案!!!

不是必定相同 ... 只能说在读取小文件的时候相同而已 ...

filesize() 函数在部分 x86 系统上读取大于 2GB 的文件会返回错误的值 ...

而 file_get_contents 的长度则是正确的 ... 但 php 的变量长度受到内存的制约 ...

如果试图用 file_get_contents 读取一个超过 php memory limit 的文件 ...

则会触发一个 PHP Fatal Error ... 导致整个程序运行中止无结果返回 ...

必定相同。(字数限制)

使用CURL发送head请求,只返回请求头信息,curl_getinfo可获取Content-Length参数

可以用stat函数,这个可以精确获取文件大小

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn