如果我在PHP中上傳兩個具有相同名稱的文件,則最新的文件將覆蓋舊版本。爲了防止這個,我寫了下面的代碼。但是,每當我從HTML選擇框中選擇Minor時,它似乎都會超時。我認爲這與我的變量$i
分配有關。有任何想法嗎?根據標準上傳文件後重命名文件
if (isset($_POST['addfile'])) {
// variables
define('UPLOAD_DIR', 'repository/');
$fileName = $_FILES['fileToUpload'];
if($_POST['rev_type'] == 'Minor') {
function update_file_name_minor($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 0.01;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i + 0.01;
}
return $file;
}
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
echo "You have successfully uploaded and renamed the file as a minor revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
elseif($_POST['rev_type'] == 'Major') {
function update_file_name_major($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 2;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
}
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
echo "You have successfully uploaded and renamed the file as a major revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
} //main if
您創建了一個無限循環。看看這背後的邏輯:'if(!file_exists($ file))exists = TRUE;' – arkascha
只是將日期字符串添加到結尾 - 這將使文件名始終唯一 – 2015-06-21 05:27:51
所以我應該將它設置爲false ?我將如何修復這個循環? @arkascha – hikaru12