在動態網站上,建立具有特定副檔名的暫存檔是很常見的需求。這種需求主要是因為 Microsoft 瀏覽器會根據檔案的副檔名來識別下載檔案的 MIME 類型。
沒有單一的 PHP 函式可以建立具有特定副檔名的暫存檔名,而且,正如已經顯示的,除非你使用 PHP 的原子基本操作,否則會出現競爭條件。
我只使用以下的基本操作,並利用作業系統相關的行為來安全地建立具有特定後綴、前綴和目錄的檔案。請享用。
<?php
function secure_tmpname($postfix = '.tmp', $prefix = 'tmp', $dir = null) {
if (! (isset($postfix) && is_string($postfix))) {
return false;
}
if (! (isset($prefix) && is_string($prefix))) {
return false;
}
if (! isset($dir)) {
$dir = getcwd();
}
$tries = 1;
do {
$sysFileName = tempnam($dir, $prefix);
if ($sysFileName === false) {
return false;
}
$newFileName = $sysFileName . $postfix;
if ($sysFileName == $newFileName) {
return $sysFileName;
}
$newFileCreated = (isWindows() ? @rename($sysFileName, $newFileName) : @link($sysFileName, $newFileName));
if ($newFileCreated) {
return $newFileName;
}
unlink ($sysFileName);
$tries++;
} while ($tries <= 5);
return false;
}
?>
isWindows 函式大部分留給讀者練習。以下是一個起點
<?php
function isWindows() {
return (DIRECTORY_SEPARATOR == '\\' ? true : false);
}
?>
如同 tempnam(),這個函式要求你稍後清理自己的檔案。在 UNIX 下(你可以重新命名成一個已存在檔案,所以我使用了 link),你必須移除連結和連結的目標。清理工作完全留給讀者自行處理。