讀取檔案函數
<?php
/**
* 讀取檔案完整內容
* @param string $file_name 檔案路徑
* @return string|false 檔案內容或 false(失敗)
*/
function readfromfile($file_name) {
if (!file_exists($file_name)) {
return false;
}
$fp = fopen($file_name, 'r');
if (!$fp) return false;
// 共享鎖(允許並發讀取)
if (!flock($fp, LOCK_SH)) {
fclose($fp);
return false;
}
$file_data = fread($fp, filesize($file_name));
flock($fp, LOCK_UN);
fclose($fp);
return $file_data;
}
寫入檔案函數
<?php
/**
* 寫入檔案
* @param string $file_name 檔案路徑
* @param string $data 要寫入的資料
* @param string $mode 'w' 覆寫 | 'a' 附加
* @return int|false 寫入位元組數或 false
*/
function writetofile($file_name, $data, $mode = 'w') {
$fp = fopen($file_name, $mode);
if (!$fp) return false;
// 獨佔鎖
if (!flock($fp, LOCK_EX)) {
fclose($fp);
return false;
}
$written = fwrite($fp, $data);
flock($fp, LOCK_UN);
fclose($fp);
return $written;
}
改進版:支援大檔案分塊讀寫
<?php
const CHUNK_SIZE = 8192; // 8KB
function read_file_chunked($filepath, callable $callback) {
if (!is_readable($filepath)) return false;
$fp = fopen($filepath, 'rb');
if (!$fp) return false;
flock($fp, LOCK_SH);
while (!feof($fp)) {
$chunk = fread($fp, CHUNK_SIZE);
if ($chunk === '') break;
$callback($chunk);
}
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
function write_file_chunked($filepath, iterable $data_chunks, $mode = 'w') {
$fp = fopen($filepath, $mode === 'a' ? 'ab' : 'wb');
if (!$fp) return false;
flock($fp, LOCK_EX);
$total = 0;
foreach ($data_chunks as $chunk) {
$written = fwrite($fp, $chunk);
if ($written === false) {
flock($fp, LOCK_UN);
fclose($fp);
return false;
}
$total += $written;
}
flock($fp, LOCK_UN);
fclose($fp);
return $total;
}
// 使用:大檔案複製不佔記憶體
read_file_chunked('large_video.mp4', function($chunk) use ($dest_fp) {
fwrite($dest_fp, $chunk);
});
現代替代:file_get_contents / file_put_contents
<?php
// 讀取(小檔案適用,大檔案會佔用記憶體)
$content = file_get_contents('config.json');
$data = json_decode($content, true);
// 寫入(支援 LOCK_EX)
file_put_contents('config.json', json_encode($data, JSON_UNESCAPED_UNICODE), LOCK_EX);
// 串流複製(大檔案、低記憶體)
$src = fopen('source.log', 'rb');
$dst = fopen('dest.log', 'wb');
stream_copy_to_stream($src, $dst);
fclose($src);
fclose($dst);
效能比較建議
| 場景 | 推薦方式 | 理由 |
| 小設定檔(<1MB) | file_get_contents / file_put_contents | 程式碼簡潔、內建鎖定選項 |
| 大檔案(>10MB) | fopen + fread/fwrite 分塊 | 固定記憶體用量、可顯示進度 |
| 高併發日誌寫入 | fopen('a') + flock(LOCK_EX) + fwrite | 附加模式無需截斷、鎖定保護 |
| 需原子性替換 | 寫暫存檔 + rename() | 避免讀到半寫入檔案 |
| 跨進程同步 | flock() 或資料庫/Redis 鎖 | flock 僅限同機器、本地檔案系統 |
錯誤處理模式
<?php
try {
$data = readfromfile('data.json');
if ($data === false) throw new Exception('讀取失敗');
$config = json_decode($data, true);
if (json_last_error() !== JSON_ERROR_NONE) throw new Exception('JSON 解析錯誤');
$config['last_update'] = time();
$result = writetofile('data.json', json_encode($config, JSON_UNESCAPED_UNICODE));
if ($result === false) throw new Exception('寫入失敗');
echo "更新成功";
} catch (Exception $e) {
error_log($e->getMessage());
http_response_code(500);
echo "系統錯誤,請稍後再試";
}