简体   繁体   中英

How to prevent a PHP upload script from overwriting existing files?

Been working my PHP upload script myself, but got stuck with prevent overwriting existing file, how to do it. Please require tips and explanation. And also please if my way to handle upload is good, if not please advise and give tips.

$destination = 'C:/upload_test/';
$max=75200;
if (isset($_POST['upload'])) {
if (isset($_FILES['image']['tmp_name'])) {
$fileTaille= $_FILES['image']['size'];
if ($fileTaille==true) {
 if ($fileTaille > $max) {
    echo "Your file is too large, select a file smaller than";
    exit(include 'form.php');
   }
 }
   else {
    echo "No file selected";
    exit(include 'form.php');
   }
}

$file_type=getimagesize($_FILES['image']['tmp_name']);

 if ($file_type==true) {
   echo "File is an image - " .$file_type["mime"]." ";
 }
  else{
    echo "Could not get file type";
  }

$fileType = exif_imagetype($_FILES['image']['tmp_name']);
$allowed = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);

 if (!in_array($fileType, $allowed)) {
   echo "File type not accepted, Only JPEG file allowed";
   exit(include 'form.php');
 }

$clean_file = preg_replace("/[^A-Z0-9\.\_-]/i", " ", $_FILES["image"]["name"]);
 $fileName = $destination . basename($clean_file);
 if (file_exists($fileName)) {
   echo "File already exist";
   exit(include 'form.php');
 }

}

if (isset($_FILES['image']['tmp_name'])) {
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination . $_FILES['image']['name']); 

  if ($result == true) {
  echo "file moved "." ";
  }else
    {
    echo "Could not move filed";
    }
$permission = chmod($destination . $clean_file, 0644);
  if ($permission==false) {
    echo "No permission to the file";
  }
   else
   {
    echo "permission given";
   }
}
?>

Best practise in my opinion is to make a sha256 of the file and then save it, this way you don't overwrite files and also you don't save duplicate files.

How to do it:

  1. Upload the files to a temporary directory
  2. Hash the file and get the sha256 string.
  3. Rename the file and copy to upload folder.

Example:

$clean_file = preg_replace("/[^A-Z0-9\.\_-]/i", " ", $_FILES["image"]["name"]);
$fileName = hash_file('sha256', $clean_file);
rename($clean_file, $fileName.$extention);

The file you are searching for and the file you are saving have different names. You are searching for a file with the name $clean_file but saving $_FILES['image']['name'] instead. You should update your code to save it as $clean_file :

$result = move_uploaded_file($_FILES['image']['tmp_name'],
    $destination . $clean_file
); 

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