我正在编写一个脚本来上传文件作为我的php项目的一部分。如果一个文件已经存在同名,而不是移动文件并覆盖其中的任何内容,我使用header()刷新页面并添加消息以在上传之前重命名该文件。
但是,它不起作用。无论名称是否已被占用,程序都会移动文件。
我测试过了
if(file_exists($_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['uploadFile']['name']))
它似乎独立工作,但不在我的程序结构中。我无法弄清楚它出了什么问题。
这是我的代码
<?php
include ('includes/openfile.php');
if(isset($_FILES['uploadFile']))
{
$allowed = array('image/JPG', 'image/jpeg', 'image/png', 'text/plain');
// validate the file type
if(in_array($_FILES['uploadFile']['type'], $allowed))
{
//check if file exists with current file name in order to prevent overwrite -- prevents overwrite .htaccess attack as well as protecting user files
if(file_exists($_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['uploadFile']['name']))
{
// file must have a unique name
header("Location: file-upload.php?msg=" . urlencode(base64_encode("Please rename this file.")));
}
else
{
// file has unique name, so move it to uploads directory
move_uploaded_file($_FILES['uploadFile']['tmp_name'], "../uploads/" . $_FILES['uploadFile']['name']);
}
}
else
{
header("Location: file-upload.php?msg=" . urlencode(base64_encode("Please upload a .JPG, .jpeg, .png, or .txt file type")));
}
// check for a file error
if($_FILES['uploadFile']['error'] > 0)
{
echo "<h1 class='jumbotron error'>There was an error because </h1>";
switch ($_FILES['uploadFile']['error'])
{
case 1:
echo "<h2 class='jumbtron'>File exceeds upload max file size</h2>";
break;
case 2:
echo "<h2 class='jumbtron'>File exeeds max file size in html form</h2>";
break;
case 3:
echo "<h2 class='jumbtron'>File was only partially uploadeded</h2>";
break;
case 4:
echo "<h2 class='jumbtron'>No file was uploaded</h2>";
break;
case 6:
echo "<h2 class='jumbtron'>No temporary folder was available</h2>";
break;
case 7:
echo "<h2 class='jumbtron'>Unable to write to the disk</h2>";
break;
case 8:
echo "<h2 class='jumbtron'>File upload stopped</h2>";
break;
default:
echo "<h2 class='jumbtron'>A system error has occured</h2>";
break;
}
}
else
{
# TODO: encrypt uploaded file
// delete tmp file
if(file_exists($_FILES['uploadFile']['tmp_name']) && is_file($_FILES['uploadFile']['tmp_name']))
{
unlink($_FILES['uploadFile']['tmp_name']);
}
// let the user know the file was succesfully uploaded
header("Location: file-upload.php?success=" . urlencode(base64_encode("File uploaded successfully!")));
}
}
include ('includes/closefile.php');
?>
感谢您的帮助!