PHP 提供豐富的檔案系統函數,掌握核心操作是後端開發基本功。本文系統整理「寫入、讀取、刪除、複製」四大核心操作,搭配錯誤處理、鎖定機制、資源管理最佳實踐。
| 模式 | 說明 | 指標位置 | 截斷檔案 | 建立新檔 |
|---|---|---|---|---|
w | 唯寫 | 開頭 | 是 | 是 |
a | 唯寫 (附加) | 結尾 | 否 | 是 |
w+ | 讀寫 | 開頭 | 是 | 是 |
a+ | 讀寫 (附加) | 結尾 | 否 | 是 |
x | 唯寫 (獨佔建立) | 開頭 | 否 | 僅不存在時 |
c | 唯寫 (不截斷) | 開頭 | 否 | 是 |
<?php
function safeWrite(string $filepath, string $data, bool $append = false): bool
{
$dir = dirname($filepath);
if (!is_dir($dir)) {
if (!mkdir($dir, 0755, true)) {
error_log("建立目錄失敗: $dir");
return false;
}
}
$flags = $append ? (LOCK_EX | FILE_APPEND) : LOCK_EX;
$bytes = file_put_contents($filepath, $data, $flags);
if ($bytes === false) {
error_log("寫入失敗: $filepath");
return false;
}
return true;
}
// 使用範例
safeWrite('logs/app.log', date('Y-m-d H:i:s') . " 用戶登入\n", true); // 附加模式
safeWrite('config/settings.json', json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); // 覆寫模式
?>
<?php
function writeLargeFile(string $source, string $dest, int $chunkSize = 8192): bool
{
$src = fopen($source, 'rb');
$dst = fopen($dest, 'wb');
if (!$src || !$dst) return false;
while (!feof($src)) {
$chunk = fread($src, $chunkSize);
if (fwrite($dst, $chunk) === false) {
fclose($src);
fclose($dst);
return false;
}
}
fclose($src);
fclose($dst);
return true;
}
?>
| 函數/方法 | 適用場景 | 記憶體 | 效能 |
|---|---|---|---|
file_get_contents() | 小檔案、API 回應、配置檔 | 全載入 | 最快 (內部優化) |
file() | 逐行處理、日誌分析 | 全載入陣列 | 中等 |
fopen() + fgets() | 大檔案逐行、CSV 解析 | 單行 | 好 |
fopen() + fread() | 二進位檔案、分塊處理 | 分塊大小 | 好 |
SplFileObject | 物件導向、CSV 迭代 | 單行 | 好 |
readfile() | 直接輸出下載、圖片代理 | 不佔用 PHP 記憶體 | 最佳 |
<?php
function importCsv(string $filepath, callable $rowHandler): int
{
$handle = fopen($filepath, 'rb');
if (!$handle) throw new Exception("無法開啟檔案: $filepath");
$count = 0;
// 設定 CSV 控制字元
while (($row = fgetcsv($handle, 0, ',', '"', '\\')) !== false) {
// 跳過空行
if (array_filter($row) === []) continue;
try {
$rowHandler($row, $count);
$count++;
} catch (Throwable $e) {
error_log("第 $count 行處理失敗: " . $e->getMessage());
// 可決定是否繼續或中止
}
}
fclose($handle);
return $count;
}
// 使用
$imported = importCsv('data/users.csv', function(array $row, int $index) {
// $row = ['姓名', 'Email', '電話', ...]
User::create([
'name' => $row[0],
'email' => $row[1],
'phone' => $row[2],
]);
});
echo "匯入 $imported 筆資料";
?>
<?php
function safeDelete(string $path): bool
{
// 正規化路徑,防止目錄遍歷
$realPath = realpath($path);
if (!$realPath || !file_exists($realPath)) {
return true; // 不存在視為成功
}
// 安全檢查:確保在允許目錄內
$allowedRoot = realpath(__DIR__ . '/storage');
if (strpos($realPath, $allowedRoot) !== 0) {
error_log("嘗試刪除受保護路徑: $realPath");
return false;
}
if (is_dir($realPath)) {
// 遞歸刪除目錄
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($realPath, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
}
return rmdir($realPath);
}
return unlink($realPath);
}
// 清理超過 30 天的暫存檔
function cleanupTemp(string $dir, int $maxAge = 2592000): int
{
$deleted = 0;
$now = time();
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile() && ($now - $file->getMTime()) > $maxAge) {
if (unlink($file->getPathname())) $deleted++;
}
}
return $deleted;
}
?>
<?php
function smartCopy(string $source, string $dest, bool $overwrite = false): bool
{
if (!file_exists($source)) {
throw new Exception("來源檔案不存在: $source");
}
if (file_exists($dest)) {
if (!$overwrite) {
throw new Exception("目標檔案已存在: $dest");
}
if (!unlink($dest)) {
throw new Exception("無法覆寫目標檔案: $dest");
}
}
$destDir = dirname($dest);
if (!is_dir($destDir)) {
mkdir($destDir, 0755, true);
}
// copy() 會自動處理大檔案串流,不佔用記憶體
if (!copy($source, $dest)) {
throw new Exception("複製失敗: $source -> $dest");
}
// 保留原檔權限與時間
$stat = stat($source);
chmod($dest, $stat['mode'] & 0777);
touch($dest, $stat['mtime']);
return true;
}
// 移動 (跨裝置自動 fallback 為複製+刪除)
function smartMove(string $source, string $dest, bool $overwrite = false): bool
{
if (!file_exists($source)) return false;
if (file_exists($dest)) {
if (!$overwrite) return false;
unlink($dest);
}
$destDir = dirname($dest);
if (!is_dir($destDir)) mkdir($destDir, 0755, true);
// 同檔案系統用 rename (原子操作、極快)
if (@rename($source, $dest)) return true;
// 跨檔案系統 fallback
return smartCopy($source, $dest, true) && unlink($source);
}
?>
<?php
class FileUtil
{
/** 取得人類可讀檔案大小 */
public static function humanSize(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
/** 取得副檔名 (小寫) */
public static function extension(string $path): string
{
return strtolower(pathinfo($path, PATHINFO_EXTENSION));
}
/** 安全檔名 (移除特殊字元) */
public static function sanitizeFilename(string $filename): string
{
$filename = basename($filename);
$filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
return substr($filename, 0, 255);
}
/** 計算檔案雜湊 (支援大檔) */
public static function hashFile(string $path, string $algo = 'sha256'): string
{
$hash = hash_init($algo);
$handle = fopen($path, 'rb');
while (!feof($handle)) {
hash_update($hash, fread($handle, 8192));
}
fclose($handle);
return hash_final($hash);
}
/** 取得 MIME 類型 */
public static function mimeType(string $path): string
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
finfo_close($finfo);
return $mime ?: 'application/octet-stream';
}
}
?>
fopen、fwrite、copy、unlink 皆可能回傳 falseerror_get_last():函數失敗時獲取詳細錯誤declare(strict_types=1) 避免隱性轉型PHP 檔案操作看似簡單,但生產環境需考慮:併發安全 (flock)、大檔記憶體管理 (串流)、路徑安全 (realpath)、錯誤處理、權限保留、跨平台相容。善用 file_put_contents() (簡單)、SplFileObject (OOP)、readfile() (輸出) 等現代 API,配合自訂工具類,能構建健壯的檔案處理層。