檔案開啟模式完整表
| 模式 | 讀/寫 | 指標位置 | 截斷 | 建立 | 失敗條件 |
| r | 唯讀 | 開頭 | 否 | 否 | 檔案不存在 |
| r+ | 讀/寫 | 開頭 | 否 | 否 | 檔案不存在 |
| w | 唯寫 | 開頭 | 是 | 是 | 權限不足 |
| w+ | 讀/寫 | 開頭 | 是 | 是 | 權限不足 |
| a | 唯寫 | 結尾 | 否 | 是 | 權限不足 |
| a+ | 讀/寫 | 結尾 | 否 | 是 | 權限不足 |
| x | 唯寫 | 開頭 | 否 | 獨佔建立 | 檔案已存在 |
| x+ | 讀/寫 | 開頭 | 否 | 獨佔建立 | 檔案已存在 |
二進位模式加 b (如 rb, wb),Windows 下文字/二進位有差異,建議**永遠加 b**。
核心讀寫函數
$fh = fopen('data.txt', 'rb');
$data = fread($fh, filesize('data.txt')); // 讀全檔
fclose($fh);
// 逐行
$fh = fopen('data.txt', 'r');
while (($line = fgets($fh)) !== false) { /* 處理 */ }
fclose($fh);
// 逐字元
$char = fgetc($fh);
// 寫入
$fh = fopen('data.txt', 'wb');
fwrite($fh, $data);
fclose($fh);
便利函數 (無需手動開關)
| 函數 | 用途 |
file_get_contents() | 整檔讀入字串 (支援 URL、stream context) |
file_put_contents() | 字串寫入檔案 (支援 FILE_APPEND、LOCK_EX) |
file() | 整檔讀入陣列 (每行一元素) |
readfile() | 直接輸出至輸出緩衝 (適合大檔下載) |
檔案鎖定 (flock)
$fh = fopen('counter.txt', 'c+');
if (flock($fh, LOCK_EX)) { // 獨佔鎖 (寫入)
$count = (int)fread($fh, filesize('counter.txt'));
$count++;
ftruncate($fh, 0);
rewind($fh);
fwrite($fh, (string)$count);
flock($fh, LOCK_UN);
} else {
echo "無法取得鎖定";
}
fclose($fh);
| 常數 | 用途 |
LOCK_SH | 共享鎖 (讀取) |
LOCK_EX | 獨佔鎖 (寫入) |
LOCK_UN | 釋放鎖 |
LOCK_NB | 非阻塞 (配合 LOCK_EX|LOCK_NB) |
指標控制
| 函數 | 用途 |
ftell($fh) | 取得目前指標位置 |
fseek($fh, $offset, $whence) | 移動指標 (SEEK_SET/CUR/END) |
rewind($fh) | 指標歸零 |
檔案資訊函數
| 函數 | 用途 |
file_exists() | 檔案/目錄是否存在 |
is_file() / is_dir() / is_link() | 型別判斷 |
filesize() | 大小 (位元組),大檔案可能不準 |
filetype() | 類型 (file/dir/link/等) |
filemtime() / fileatime() / filectime() | 修改/存取/狀態改變時間 |
fileperms() | 權限位元遮罩 |
fileowner() / filegroup() | 擁有者 UID/GID |
is_readable() / is_writable() / is_executable() | 權限檢查 |
檔案/目錄操作
copy($src, $dest); // 複製檔案
unlink($file); // 刪除檔案
rename($old, $new); // 移動/重命名
mkdir($path, 0755, true); // 遞迴建立目錄
rmdir($dir); // 刪除空目錄
chmod($file, 0644); // 修改權限
chown($file, $uid); // 修改擁有者
chgrp($file, $gid); // 修改群組
touch($file); // 更新時間或建立空檔
clearstatcache(); // 清除 stat 快取
計數器完整範例
function hitCounter($file = 'counter.txt') {
if (!file_exists($file)) {
file_put_contents($file, '0', LOCK_EX);
}
$fh = fopen($file, 'c+');
flock($fh, LOCK_EX);
$count = (int)fread($fh, filesize($file));
$count++;
ftruncate($fh, 0);
rewind($fh);
fwrite($fh, (string)$count);
flock($fh, LOCK_UN);
fclose($fh);
return $count;
}
echo "您是第 " . hitCounter() . " 位訪客";