在PHP中获取大文件(> 2 GB)文件大小的最佳方法?

时间:2013-05-31 22:00:19

标签: php file filesize

我正在处理PHP中的大文件,并且需要一种可靠的方法来获取超过4 GB的较大文件的文件大小,但PHP遇到了超过2 GB的文件的问题...到目前为止,我只看到涉及的解决方案命令行exec功能,但该脚本将用作独立的控制台应用程序,因此,我对使用exec有点犹豫,因为它可能在不同平台上有不同的反应。我看到的唯一方法是读取所有数据并计算字节数,但这将非常慢......我需要一种快速可靠的方法,它将在许多不同的计算机(Linux,Windows,Mac)上做出同样的反应。

2 个答案:

答案 0 :(得分:2)

这个先前提出的问题看起来非常相似,并且有一些你可以探索的想法: PHP x86 How to get filesize of > 2 GB file without external program?

在其中,作者提出了一个他在GitHub上托管的解决方案,链接位于:https://github.com/jkuchar/BigFileTools/blob/master/src/BigFileTools.php

除此之外,您运行的是32位系统,因此http://php.net/manual/en/function.filesize.php的PHP中的文件超过2 GB会很麻烦:

  

注意:因为PHP的整数类型已签名且许多平台都使用   32位整数,某些文件系统函数可能会返回意外   文件的结果大于2GB。

答案 1 :(得分:-2)

下面的代码适用于任何版本的PHP / OS / Webserver / Platform上的任何文件大小。

// http head request to local file to get file size
$opts = array('http'=>array('method'=>'HEAD'));
$context = stream_context_create($opts);

// change the URL below to the URL of your file. DO NOT change it to a file path.
// you MUST use a http:// URL for your file for a http request to work
// SECURITY - you must add a .htaccess rule which denies all requests for this database file except those coming from local ip 127.0.0.1.
// $tmp will contain 0 bytes, since its a HEAD request only, so no data actually downloaded, we only want file size
$tmp= file_get_contents('http://127.0.0.1/pages-articles.xml.bz2', false, $context);

$tmp=$http_response_header;
foreach($tmp as $rcd) if( stripos(trim($rcd),"Content-Length:")===0 )  $size= floatval(trim(str_ireplace("Content-Length:","",$rcd)));
echo "File size = $size bytes";

// example output .... 9 GB local file
File size = 10082006833 bytes
相关问题