我有一个非常大的文件(大约20GB),如何使用fseek()跳转并阅读其内容。
代码如下所示:
function read_bytes($f, $offset, $length) {
fseek($f, $offset);
return fread($f, $length);
}
结果只有在$ offset< 2147483647。
更新:我在Windows 64上运行, phpinfo - 架构:x64, PHP_INT_MAX:2147483647
答案 0 :(得分:5)
警告:如评论中所述,fseek在内部使用INT,它根本无法工作 在32位PHP编译上有如此大的文件。以下解决方案 不会工作。它留在这里仅供参考。
一点点搜索引导我对fseek的PHP手册页面发表评论:
http://php.net/manual/en/function.fseek.php
问题是offset参数的最大int大小,但似乎你可以通过使用SEEK_CUR选项执行多个fseek调用并将其与大数字处理库之一混合来解决它。
示例:
function fseek64(&$fh, $offset)
{
fseek($fh, 0, SEEK_SET);
$t_offset = '' . PHP_INT_MAX;
while (gmp_cmp($offset, $t_offset) == 1)
{
$offset = gmp_sub($offset, $t_offset);
fseek($fh, gmp_intval($t_offset), SEEK_CUR);
}
return fseek($fh, gmp_intval($offset), SEEK_CUR);
}
fseek64($f, '23456781232');
答案 1 :(得分:3)
对于我的项目,我需要从BIG文件(> 3 GB)中的BIG偏移读取10KB的块。写入总是附加,因此不需要抵消。
这将起作用,无论您使用的是哪个PHP版本和操作系统。
先决条件=您的服务器应支持范围检索查询。 Apache& IIS已经支持这一点,99%的其他Web服务器(共享托管或其他)
也是如此// offset, 3GB+
$start=floatval(3355902253);
// bytes to read, 100 KB
$len=floatval(100*1024);
// set up the http byte range headers
$opts = array('http'=>array('method'=>'GET','header'=>"Range: bytes=$start-".($start+$len-1)));
$context = stream_context_create($opts);
// bytes ranges header
print_r($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
// this will output the results
echo $result = file_get_contents('http://127.0.0.1/dir/mydbfile.dat', false, $context);
// status of your request
// if this is empty, means http request didnt fire.
print_r($http_response_header);
// Check your file URL and verify by going directly to your file URL from a web
// browser. If http response shows errors i.e. code > 400 check you are sending the
// correct Range headers bytes. For eg - if you give a start Range which exceeds the
// current file size, it will give 406.
// NOTE - The current file size is also returned back in the http response header
// Content-Range: bytes 355902253-355903252/355904253, the last number is the file size
...
...
...
安全 - 您必须添加.htaccess规则,该规则拒绝对此数据库文件的所有请求,但来自本地IP 127.0.0.1的请求除外。