8

I'm uploading multiple files. Main function works fine, but I have to change the names of uploading files Like: name1.jpg, name2.jps, name3.jpg, ...

$i = 1;
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/name'.$i++.'.'.$extension)){
     echo '{"status":"success"}';
     exit;
}

Number $i should grow with amount of uploaded files. I hope that explained it correctly.

tomloprod
  • 7,472
  • 6
  • 48
  • 66

1 Answers1

8

You need a loop:

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

     $name_array = $_FILES['files']['name'];
     $tmp_name_array = $_FILES['files']['tmp_name'];
     // Number of files
     $count_tmp_name_array = count($tmp_name_array);

     // We define the static final name for uploaded files (in the loop we will add an number to the end)
     $static_final_name = "name";

     for($i = 0; $i < $count_tmp_name_array; $i++){
          // Get extension of current file
          $extension = pathinfo($name_array[$i] , PATHINFO_EXTENSION);

          // Pay attention to $static_final_name 
          if(move_uploaded_file($tmp_name_array[$i], "uploads/".$static_final_name.$i.".".$extension)){
               echo $name_array[$i]." upload is complete<br>";
          } else {
               echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
          }

     }

}
tomloprod
  • 7,472
  • 6
  • 48
  • 66
  • What if I want to use a timestamp instead of .$static_final_name.$i.? – Samuel Ramzan Jun 24 '20 at 03:56
  • @SamuelRamzan You could have problems, since the timestamp change every second and it is possible that several files are uploaded in a single second, so you would find that they would be overwritten – tomloprod Jun 24 '20 at 06:16
  • You could use: `$uniqueFileName = uniqid(mt_rand(), true);`. See my answer here https://stackoverflow.com/a/41594109 – tomloprod Jun 24 '20 at 06:18