檔案操作是後端開發核心技能。本系列分三篇涵蓋:讀取/判斷存在 (本篇)、寫入/鎖定/複製/屬性 (第 2 篇)、串流/大檔案/權限/臨時檔 (第 3 篇)。
<?php
$file = 'data/config.json';
// file_exists(): 檢查檔案/目錄是否存在 (含連結)
if (!file_exists($file)) {
die("檔案不存在: $file");
}
// is_readable(): 檢查是否可讀 (權限 + 存在)
if (!is_readable($file)) {
die("檔案不可讀: $file");
}
// is_file() / is_dir(): 區分檔案與目錄
if (is_file($file)) echo "是檔案\n";
if (is_dir($file)) echo "是目錄\n";
// 實務建議:直接嘗試開啟,失敗再處理 (避免 TOCTOU 競態)
$fp = @fopen($file, 'r');
if (!$fp) {
die("無法開啟檔案: $file (權限或不存在)");
}
?>
| 方法 | 適用場景 | 記憶體 | 備註 |
|---|---|---|---|
file_get_contents() | 中小型檔案 (<100MB)、簡單讀取 | 一次載入全部 | PHP 4.3+,支援 URL、串流 |
file() | 逐行處理文字檔 | 一次載入全部行陣列 | 保留換行符,可配合 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES |
fopen() + fread() | 大檔案、二進位、需控制位置 | 可分塊讀取 | 需手動 fclose() |
stream_get_contents() | 從資源讀取剩餘內容 | 一次載入 | 配合 fopen() 使用 |
<?php
$file = 'data/large.log';
// A. file_get_contents (簡單)
$content = file_get_contents($file);
echo "長度: " . strlen($content) . "\n";
// B. file() 逐行陣列
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
echo "行數: " . count($lines) . "\n";
// C. fopen + fread (二進位/大檔案)
$fp = fopen($file, 'rb'); // b 標誌: 二進位模式 (Windows 重要)
if ($fp) {
$size = filesize($file);
$chunk = 8192;
while (!feof($fp)) {
$data = fread($fp, $chunk);
// 處理 $data (如寫入輸出緩衝、解析、加密...)
// echo $data; // 直接輸出
}
fclose($fp);
}
// D. 讀取特定位移/長度 (隨機存取)
$fp = fopen($file, 'rb');
fseek($fp, 100); // 移動到位元組 100
$segment = fread($fp, 50); // 讀 50 位元組
fclose($fp);
?>
<?php
$fp = fopen('data/users.csv', 'r');
if ($fp) {
// 可選:設定編碼轉換 (如 Big5 轉 UTF-8)
// stream_filter_append($fp, 'convert.iconv.big5/utf-8');
$header = fgetcsv($fp); // 讀取標題行
while (($row = fgetcsv($fp)) !== false) {
$record = array_combine($header, $row);
// 處理 $record
print_r($record);
}
fclose($fp);
}
?>
<?php
$file = 'data/counter.txt';
$fp = fopen($file, 'c+'); // c+ : 開啟讀寫,不存在則建立,指標在開頭
if ($fp) {
// 獨佔鎖定 (阻塞直到取得)
if (flock($fp, LOCK_EX)) {
$count = (int)fread($fp, filesize($file));
$count++;
ftruncate($fp, 0); // 清空檔案
rewind($fp); // 指標回開頭
fwrite($fp, (string)$count);
fflush($fp); // 刷新緩衝
flock($fp, LOCK_UN); // 釋放鎖
echo "計數器: $count\n";
} else {
echo "無法取得鎖定\n";
}
fclose($fp);
}
?>
鎖定類型: LOCK_SH 共享鎖(讀)、LOCK_EX 獨佔鎖(寫)、LOCK_NB 非阻塞(配合其他旗標)、LOCK_UN 釋放。
<?php
// 讀取圖片轉 Base64
$img = 'image.png';
$data = file_get_contents($img);
$base64 = base64_encode($data);
$mime = mime_content_type($img);
echo "
";
// 寫入二進位資料
$fp = fopen('output.bin', 'wb');
fwrite($fp, pack('H*', 'deadbeef')); // 寫入十六進位位元組
fwrite($fp, chr(0xFF) . chr(0x00)); // 寫入單一位元組
fclose($fp);
?>
| 錯誤 | 原因 | 修正 |
|---|---|---|
fopen() 失敗無錯誤訊息 | 未檢查回傳值、未啟用錯誤報告 | 用 @fopen() 抑制警告並檢查 === false,或設定 error_reporting(E_ALL) |
| Windows 下讀取二進位檔案截斷 | 未加 b 模式 (rb, wb) | 二進位檔案務必加 b |
file_get_contents() 記憶體耗盡 | 檔案過大超過 memory_limit | 改用 fopen() 分塊讀取或串流處理 |
| 檔案鎖定無效 (NFS/網路磁碟) | flock() 在某些網路檔案系統不支援 | 改用資料庫鎖、Redis 分散式鎖、或檔案系統專屬鎖機制 |
第 2 篇將涵蓋:寫入/附加、檔案複製/移動/刪除、檔案屬性修改 (chmod/chown)、目錄掃描與串流過濾器。