如何重命名上传的多个图像,以便不替换现有文件

时间:2015-05-09 13:04:19

标签: php image

我有一个网站,用户可以上传多个图像我遇到问题,因为新上传的文件正在替换图像目录中具有相同名称的现有文件。请帮助我是php的新手

if(isset($ _ FILES [' images']))         {

  foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name)
        {
                $target = "../uploads/";
                $target = $target.$_FILES['images']['name'][$key];
                if(move_uploaded_file($tmp_name, $target))
                {
                  $fname=$_FILES['images']['name'][$key];
                  $target = "PostAd/uploads/". $fname;

                mysql_query("INSERT INTO `upload_data`(`clid`, `id`, `Imgpath`,`target`) VALUES ('$clid','$id','$fname','$target')");
                  $target="";
                 }
          }
if ($sql){
     header( "Location: /Myconnec/PostAd/CampusLife/confirm.php?clid=$clid");
     ob_end_flush();
   } else {
     $error_msg = 'ERROR: Problems arose during the information exchange, please try again later.';
   }    

1 个答案:

答案 0 :(得分:0)

你可以添加这样的时间戳......

if (isset($_FILES['images'])) {

  foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name)
        {
                $target = $target.$_FILES['images']['name'][$key];
                $ext = pathinfo($target, PATHINFO_EXTENSION);
                $rand =  rand();
                $strip_ext = substr($target, 0, strlen($target) - strlen($ext));
                $timestamp =  str_replace(" ","",microtime());
                $target = "$strip_ext.$timestamp.$rand.$ext";
                if(move_uploaded_file($tmp_name, "../upload/$target"))
                {
                  $fname=$_FILES['images']['name'][$key];
                  $target = "PostAd/uploads/".$target;
                  mysql_query("INSERT INTO `upload_data`(`clid`, `id`, `Imgpath`,`target`) VALUES ('$clid','$id','$fname','$target')");
                  $target="";
                 }
          }
if ($sql){
     header( "Location: /Myconnec/PostAd/CampusLife/confirm.php?clid=$clid");
     ob_end_flush();
   } else {
     $error_msg = 'ERROR: Problems arose during the information exchange, please try again later.';
   }