[英]PHP - How to prevent override of existing files with filename increment?
I am trying my hand at a simple file-upload PHP script with a bit of file validity checking. 我正在尝试一个简单的文件上传PHP脚本,并进行了一些文件有效性检查。 This is the simple W3C example with an added while loop to check if a file exists and then to add an increment to the end of the file name (just before the file extension). 这是一个简单的W3C示例,其中添加了while循环,以检查文件是否存在,然后在文件名的末尾(文件扩展名之前)添加一个增量。
The script works, but will only produce 1 increment. 该脚本有效,但只会产生1个增量。 For example, I upload a file called 'test.jpg', it uploads, I re-upload the same file and the script produces 'test1.jpg' -- but after that, the script will just keep rewriting 'test1.jpg'! 例如,我上传了一个名为“ test.jpg”的文件,它上传了,我重新上传了相同的文件,脚本生成了“ test1.jpg”-但是之后,脚本将继续重写“ test1.jpg” !
What am I possibly doing wrong here? 我在这里可能做错了什么?
<?php
$allowedExts = array("ai", "esp", "jpg", "jpeg", "png", "tiff");
$temp = explode(".", $_FILES["file"]["name"]);
$name = pathinfo($_FILES["file"]["name"], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$i = '';
if ((($_FILES["file"]["type"] == "image/ai")
|| ($_FILES["file"]["type"] == "image/esp")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/tiff"))
&& ($_FILES["file"]["size"] < 50000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
while(file_exists("upload/" . $_FILES["file"]["name"] . $i)) {
$i++;
}
$basename = $name . $i . '.' . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $basename);
} else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
} else
{
echo "Invalid file";
}
?>
First of all you should init the $i
variable with a value of 0
not ''
(empty string). 首先,您应该将值0
而不是''
(空字符串)初始化$i
变量。
After that you may check for 之后,您可以检查
if(file_exists("upload/" . $name . $i . '.' . $extension)) { /* .... */ }
Because you move the file to 因为您将文件移动到
$basename = $name . $i . '.' . $extension;
afterwards. 然后。 So if you upload test.jpg
you check if upload/test.jpg
already exists. 因此,如果您上传test.jpg
请检查是否已经存在upload/test.jpg
。 If yes you go into a while
-loop and check of the file upload/test.jpg1
already exists. 如果是,则进入while
-loop并检查文件upload/test.jpg1
已存在。 If no then you move the uploaded file to upload/test1.jpg
. 如果否,则将上传的文件移动到upload/test1.jpg
。
Next time you check again if the file upload/test.jpg1
already exists. 下次您再次检查文件upload/test.jpg1
已经存在。 And it doesn't. 事实并非如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.