PHP:fseek()用于大文件(> 2GB)

anv*_*voz 5 php

我有一个非常大的文件(约20GB),我如何使用fseek()跳转并阅读其内容.

代码如下所示:

function read_bytes($f, $offset, $length) {
    fseek($f, $offset);
    return fread($f, $length);
}
Run Code Online (Sandbox Code Playgroud)

结果只有在$ offset <2147483647时才正确.

更新:我在Windows 64上运行,phpinfo - 架构:x64,PHP_INT_MAX:2147483647

fsw*_*fsw 5

警告:如评论中所述,fseek在内部使用INT,它无法在32位PHP编译中使用如此大的文件.以下解决方案不会工作.它留在这里仅供参考.

一点点的搜索引导我对fseek的PHP手册页进行评论:

http://php.net/manual/en/function.fseek.php

问题是偏移参数的最大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');
Run Code Online (Sandbox Code Playgroud)

  • 我今天试过这个,在32位系统上不起作用,那是因为内部fseek使用INT来存储当前文件指针而INT不能超过2G. (4认同)

Adm*_*com 3

对于我的项目,我需要从大文件(> 3 GB)中的大偏移量读取 10KB 的块。写入始终是附加的,因此不需要偏移量。

无论您使用哪个 PHP 版本和操作系统,这都会起作用。

先决条件=您的服务器应该支持范围检索查询。Apache 和 IIS 已经支持这一点,99% 的其他网络服务器(共享托管或其他)也支持这一点

// 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

...
Run Code Online (Sandbox Code Playgroud)

...

...

安全 - 您必须添加 .htaccess 规则,该规则拒绝对此数据库文件的所有请求(来自本地 IP 127.0.0.1 的请求除外)。