面對 CSDN 等億級資料洩漏的 SQL 檔(數百 MB 至數 GB),file()、file_get_contents() 會耗盡記憶體導致致命錯誤。正解是使用 fopen() + fseek() + fread() 進行流式分塊讀取,配合游標記憶實現斷點續讀。
function readBigFile($filename, $count = 20, $tag = "\n") {
$content = '';
$step = 8192; // 每次讀取 8KB
$tagLen = strlen($tag);
$start = 0;
$i = 0;
$handle = fopen($filename, 'r'); // 唯讀模式即可
while ($i < $count && !feof($handle)) {
fseek($handle, $start, SEEK_SET);
$chunk = fread($handle, $step);
if ($chunk === false) break;
$content .= $chunk;
$start += $step;
// 檢查緩衝區尾部是否包含分隔符
$tail = substr($content, -$tagLen);
if ($tail === $tag) {
$i++;
$content .= '<br />'; // 示意換行
}
}
fclose($handle);
return $content;
}
// 使用
$filename = "csdn.sql";
$tag = "\n"; // Linux/Unix 換行;Windows 用 "\r\n",Mac OS 9 用 "\r"
$data = readBigFile($filename, 100, $tag);
echo $data;
\r\n、Linux/Unix \n、Mac OS 9 \r,必須根據來源檔案調整 $tag。fseek 移動檔案指標極快(不讀取資料),適合隨機存取。// 記錄位置到檔案/資料庫/Redis
$positionFile = $filename . '.pos';
$lastPos = file_exists($positionFile) ? (int)file_get_contents($positionFile) : 0;
$handle = fopen($filename, 'r');
fseek($handle, $lastPos); // 從上次位置繼續
$batchSize = 10000; // 每批處理行數
$processed = 0;
while (!feof($handle) && $processed < $batchSize) {
$line = fgets($handle);
if ($line === false) break;
// 處理 $line:解析、入庫、統計...
$processed++;
}
$newPos = ftell($handle); // 取得當前指標位置
file_put_contents($positionFile, $newPos);
fclose($handle);
匯入超大 SQL 檔時,Navicat Premium 能流式讀取並執行,不會像 MySQL Workbench 或命令列 source 那樣吃光記憶體。支援 MySQL、PostgreSQL、Oracle、SQL Server、SQLite 等多種資料庫。
file_get_contents() + explode() 或 file() 皆可。fopen() + fgets() 逐行處理,記憶體常數級。fseek() + fread() + 位置持久化。LOAD DATA INFILE、mysqlbinlog 等原生工具。