sys_get_temp_dir(): string 返回 PHP 預設儲存臨時檔案的目錄絕對路徑(PHP 5.2.1+),跨平台相容,避免硬編碼 /tmp 或 C:\Windows\Temp。
/tmp、/var/tmpC:\Windows\Temp、C:\Users\USER\AppData\Local\Temp<?php $temp_file = tempnam(sys_get_temp_dir(), 'myapp_'); // 例如: /tmp/myapp_abc123.tmp $fp = fopen($temp_file, 'w'); fwrite($fp, "臨時資料內容"); fclose($fp); // 處理完畢後清理 unlink($temp_file); ?>
<?php
$chunk_dir = sys_get_temp_dir() . '/upload_chunks_' . session_id();
if (!is_dir($chunk_dir)) mkdir($chunk_dir, 0700, true);
$chunk_file = $chunk_dir . '/chunk_' . $_POST['chunk_index'];
file_put_contents($chunk_file, file_get_contents('php://input'));
// 合併邏輯...
?>
<?php
// 簡化版邏輯
function sys_get_temp_dir_polyfill() {
// 1. 環境變數優先順序
foreach (['TMPDIR', 'TMP', 'TEMP'] as $env) {
if (!empty($_ENV[$env])) return realpath($_ENV[$env]);
if (!empty(getenv($env))) return realpath(getenv($env));
}
// 2. 建立臨時檔案反推目錄
$temp = tempnam(uniqid('php_', true), '');
if ($temp) {
unlink($temp);
return realpath(dirname($temp));
}
// 3. 最後備援
return '/tmp';
}
?>
tempnam()、uniqid()、random_bytes() 產生唯一檔名chmod($file, 0600) 限制權限find /tmp -name 'myapp_*' -mtime +1 -delete)/tmp 檔案,機密資料勿落地| 函數 | 用途 | 自動清理 |
|---|---|---|
| tempnam() | 建立唯一臨時檔案 | 否,需手動 unlink |
| tmpfile() | 建立匿名臨時檔案資源 | 是,fclose/腳本結束自動刪除 |
| sys_get_temp_dir() | 取得臨時目錄路徑 | 不適用 |
PHP 5.2.1+ 內建,舊版專案可用上方 polyfill 相容。現代框架(Laravel, Symfony)皆封裝為 storage_path('temp') 或 kernel.getCacheDir,建議使用框架抽象層而非直接呼叫。