本文與 ID 66697 內容高度重疊,此處針對實戰中常見的進階場景補充:流式處理大文件、CSV 解析、目錄權限遞歸設置、原子寫入、文件鎖防併發、上傳安全、臨時文件管理。
<?php
function readLargeFileLines($filePath, callable $callback) {
$fp = fopen($filePath, 'rb');
if (!$fp) throw new RuntimeException("無法打開文件: $filePath");
try {
while (($line = fgets($fp)) !== false) {
$callback(rtrim($line, "\r\n"));
}
} finally {
fclose($fp);
}
}
// 使用:逐行處理 10GB 日志
readLargeFileLines('/var/log/nginx/access.log', function($line) {
if (strpos($line, ' 500 ') !== false) {
// 處理 500 錯誤行
}
});
?>
<?php
function importCsvToDb($csvPath, PDO $pdo, string $table, array $columns, int $batchSize = 1000) {
$fp = fopen($csvPath, 'rb');
if (!$fp) throw new RuntimeException("CSV 打開失敗");
$pdo->beginTransaction();
$stmt = null;
$count = 0;
try {
// 跳過標題行
fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
if ($stmt === null) {
$placeholders = implode(',', array_fill(0, count($columns), '?'));
$stmt = $pdo->prepare("INSERT INTO $table (" . implode(',', $columns) . ") VALUES ($placeholders)");
}
$stmt->execute($row);
if (++$count % $batchSize === 0) {
$pdo->commit();
$pdo->beginTransaction();
}
}
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
} finally {
fclose($fp);
}
return $count;
}
?>
<?php
function atomicWrite(string $filePath, string $data): bool {
$dir = dirname($filePath);
$tmpName = $dir . '/' . basename($filePath) . '.tmp.' . uniqid('', true);
$fp = fopen($tmpName, 'wb');
if (!$fp) return false;
$bytes = fwrite($fp, $data);
fclose($fp);
if ($bytes === false) {
@unlink($tmpName);
return false;
}
// rename 在同一文件系統上是原子操作
return @rename($tmpName, $filePath);
}
// 使用
atomicWrite('/var/www/config.json', json_encode($config, JSON_PRETTY_PRINT));
?>
<?php
function chmodRecursive(string $path, int $dirMode = 0755, int $fileMode = 0644): void {
if (is_dir($path)) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
@chmod($item->getPathname(), $item->isDir() ? $dirMode : $fileMode);
}
@chmod($path, $dirMode); // 根目錄自身
}
}
// 部署後調用
chmodRecursive('/var/www/html/storage');
chmodRecursive('/var/www/html/bootstrap/cache');
?>
<?php
$lockFile = '/tmp/my_cron_job.lock';
$fp = fopen($lockFile, 'wb');
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
exit("另一個實例正在運行,退出\n");
}
// 註冊關閉函數釋放鎖
register_shutdown_function(function() use ($fp) {
flock($fp, LOCK_UN);
fclose($fp);
@unlink($lockFile);
});
// 核心業務邏輯
echo "開始執行任務...\n";
sleep(10);
echo "任務完成\n";
?>
<?php
function handleUpload(array $file, string $uploadDir, array $allowedMimes, int $maxSize = 5_000_000): array {
// 1. 錯誤碼
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException("上傳錯誤: {$file['error']}");
}
// 2. 大小
if ($file['size'] > $maxSize) {
throw new RuntimeException("文件過大 (>{$maxSize} bytes)");
}
// 3. MIME 類型驗證 (finfo 比 $_FILES['type'] 可靠)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, $allowedMimes, true)) {
throw new RuntimeException("類型不允許: $mime");
}
// 4. 擴展名白名單 (雙重保險)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
if (!in_array($ext, $allowedExts, true)) {
throw new RuntimeException("擴展名不允許: $ext");
}
// 5. 生成安全文件名
$newName = bin2hex(random_bytes(16)) . ".$ext";
$destPath = rtrim($uploadDir, '/') . "/$newName";
// 6. 移動 (必須用 move_uploaded_file)
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
throw new RuntimeException("移動失敗");
}
// 7. 設置權限 (去除執行權限)
chmod($destPath, 0644);
return ['path' => $destPath, 'name' => $newName, 'mime' => $mime, 'size' => $file['size']];
}
// 使用
try {
$info = handleUpload($_FILES['avatar'], '/var/www/uploads', ['image/jpeg', 'image/png', 'image/webp']);
echo "上傳成功: {$info['name']}";
} catch (Exception $e) {
echo "失敗: " . $e->getMessage();
}
?>
<?php
// sys_get_temp_dir() 獲取系統臨時目錄
$tmpFile = tempnam(sys_get_temp_dir(), 'myapp_');
if ($tmpFile) {
file_put_contents($tmpFile, "臨時數據");
// ... 處理 ...
// 手動刪除或註冊關閉函數
register_shutdown_function('unlink', $tmpFile);
}
// 或使用 tmpfile() 創建匿名臨時文件 (關閉句柄自動刪除)
$tmp = tmpfile();
fwrite($tmp, "數據");
fseek($tmp, 0);
echo fread($tmp, 1024);
fclose($tmp); // 自動刪除
?>
filemtime、filesize 結果 (如 Composer autoload 緩存)。opcache.enable_cli=1 加速 CLI 腳本文件載入。文件操作看似基礎,實則暗藏併發、安全、性能、跨平台等諸多陷阱。掌握流式處理、原子寫入、安全上傳、鎖機制、臨時文件管理等進階模式,能讓你的 PHP 應用在文件密集型場景下穩健高效運行。