簡體   English   中英

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

[英]PHP: fseek() for large file (>2GB)

我有一個非常大的文件(大約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

警告:如評論中所述,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');

對於我的項目,我需要從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的請求除外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM