How to handle multiple file uploads in PHP?

Spread the love

Sometimes, we want to handle multiple file uploads in PHP.

In this article, we’ll look at how to handle multiple file uploads in PHP.

How to handle multiple file uploads in PHP?

To handle multiple file uploads in PHP, we can loop through the $_FILES array to get all the uploaded files.

For instance, if we have a file input

<input name="upload[]" type="file" multiple="multiple" />

Then we write

$total = count($_FILES['upload']['name']);

for($i=0 ; $i < $total ; $i++) {
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
  if ($tmpFilePath != ""){
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {
      // ...
    }
  }
}

to create a for loop that loops through $_FILES['upload']['name'].

We get the templ file path with $_FILES['upload']['tmp_name'][$i].

And the we get the file path to save the file to with

$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

And then we call move_uploaded_file to move the file from $tmpFilePath to $newFilePath.

Conclusion

To handle multiple file uploads in PHP, we can loop through the $_FILES array to get all the uploaded files.

Leave a Reply

Your email address will not be published. Required fields are marked *