如何防止PHP上传脚本覆盖现有文件?

时间:2015-08-08 10:42:05

标签: php file

我自己正在处理我的PHP上传脚本,但是因为阻止覆盖现有文件而陷入困境,如何做到这一点。请索取提示和解释。如果我处理上传的方式很好,如果没有,请告知并给出提示。

$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";
   }
}
?>

2 个答案:

答案 0 :(得分:0)

我认为最佳做法是制作文件的sha256然后保存,这样就不会覆盖文件,也不会保存重复的文件。

怎么做:

  1. 将文件上传到临时目录
  2. 散列文件并获取sha256字符串。
  3. 重命名文件并复制到上传文件夹。
  4. 示例:

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

答案 1 :(得分:0)

您要搜索的文件和保存的文件名称不同。您正在搜索名为$clean_file但保存$_FILES['image']['name']的文件。您应该更新代码以将其另存为$clean_file

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