How can multiple file uploads be implemented in PHP?

To achieve multi-file upload in PHP, you can do so by using an HTML form and handling the uploaded files in PHP. Here is a simple example code:

  1. Create an HTML form for file upload.
<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple>
    <input type="submit" value="Upload Files">
</form>
  1. Create a PHP script to handle uploaded files.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $files = $_FILES['file'];
    
    foreach ($files['name'] as $key => $name) {
        $tmp_name = $files['tmp_name'][$key];
        $upload_dir = "uploads/";
        
        if (move_uploaded_file($tmp_name, $upload_dir . $name)) {
            echo "File uploaded successfully: " . $name . "<br>";
        } else {
            echo "Error uploading file: " . $name . "<br>";
        }
    }
}
?>

In the code above, we first check if it is a POST request, then retrieve the uploaded file array. Next, we use a foreach loop to iterate through each file and move them to the designated upload directory. Finally, we display a message indicating whether the upload was successful or not.

Please make sure to create a folder named “uploads” on the server to store uploaded files. Additionally, ensure that the server is properly configured to allow file uploads.

This way, you will be able to achieve the functionality of uploading multiple files. I hope this can help you. If you have any questions, please feel free to ask.

Leave a Reply 0

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