如果已在PHP中上传[具有相同名称],则重命名照片名称

时间:2014-06-11 19:52:10

标签: php image-uploading

我试图解决这个问题。但我无法解决这个问题。 每次新照片替换旧照片,如果相同的名称:( 这是我的代码

      $uploads_dir = '/photo/';

      echo $_FILES["photo"]["name"]; 
      echo $_FILES["photo"]["size"];
      echo $_FILES["photo"]["type"];
      $pname = $_FILES["photo"]["name"]; 
      $tname=$_FILES["photo"]["tmp_name"];

      $name = pathinfo($_FILES['photo']['name'], PATHINFO_FILENAME);
      $extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);

       $increment = ''; //start with no suffix

       while(file_exists($name . $increment . '.' . $extension)) {
         $increment++;
     $pname = $name . $increment . '.' . $extension;

        }
        move_uploaded_file($tname, $uploads_dir.$pname);

我想要的输出是这样的 如果我上传图片名称" new.jpg" 3次...... 这些图像不会互相覆盖......这些图像将被存储为new.jpg,new1.jpg,new2.jpg

1 个答案:

答案 0 :(得分:3)

试试这个:

  $uploads_dir = '/photo/';

  echo $_FILES["photo"]["name"]; 
  echo $_FILES["photo"]["size"];
  echo $_FILES["photo"]["type"];
  $pname = $_FILES["photo"]["name"]; 
  $tname=$_FILES["photo"]["tmp_name"];

  $name = pathinfo($_FILES['photo']['name'], PATHINFO_FILENAME);
  $extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);

   $increment = 0; 
   $pname = $name . '.' . $extension;
   while(is_file($uploads_dir.'/'.$pname)) {
     $increment++;
     $pname = $name . $increment . '.' . $extension;
   }
   move_uploaded_file($tname, $uploads_dir.'/'.$pname);