简体   繁体   中英

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. 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).

The script works, but will only produce 1 increment. 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'!

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).

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. If yes you go into a while -loop and check of the file upload/test.jpg1 already exists. If no then you move the uploaded file to upload/test1.jpg .

Next time you check again if the file upload/test.jpg1 already exists. And it doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM