How to Handle Multiple File Upload in PHP Easily
name="files[]" attribute in your HTML form input and loop through the $_FILES['files']['name'] array in PHP. This lets you process each uploaded file individually by accessing its temporary name, error status, and other details.Why This Happens
When you try to upload multiple files using a single file input without using the array syntax name="files[]", PHP treats it as a single file upload. This causes errors or only one file to be processed.
Also, if you try to access $_FILES['files']['name'] as a string instead of an array, your code will break or ignore other files.
<?php if (isset($_FILES['files'])) { // Incorrect: treating as single file $fileName = $_FILES['files']['name']; move_uploaded_file($_FILES['files']['tmp_name'], 'uploads/' . $fileName); echo "Uploaded: " . $fileName; } ?>
The Fix
Use name="files[]" in your HTML input to allow multiple files. Then, in PHP, loop through the $_FILES['files']['name'] array to handle each file separately. Check for upload errors and move each file to your desired folder.
<form method="POST" enctype="multipart/form-data"> <input type="file" name="files[]" multiple> <button type="submit">Upload</button> </form> <?php if (isset($_FILES['files'])) { $totalFiles = count($_FILES['files']['name']); for ($i = 0; $i < $totalFiles; $i++) { $fileName = $_FILES['files']['name'][$i]; $tmpName = $_FILES['files']['tmp_name'][$i]; $error = $_FILES['files']['error'][$i]; if ($error === UPLOAD_ERR_OK) { move_uploaded_file($tmpName, 'uploads/' . $fileName); echo "Uploaded: " . htmlspecialchars($fileName) . "<br>"; } else { echo "Error uploading " . htmlspecialchars($fileName) . "<br>"; } } } ?>
Prevention
Always use the multiple attribute and name="files[]" in your file input to enable multiple uploads. Validate each file's size and type before saving. Use error checks like UPLOAD_ERR_OK to handle upload problems gracefully. Keep your upload folder secure and avoid overwriting files by renaming if needed.
Related Errors
- Undefined index 'files': Happens if the form input name does not match or form enctype is missing.
- File upload size exceeds limit: Check
php.inisettings likeupload_max_filesizeandpost_max_size. - Permission denied: Ensure the upload folder has write permissions.
Key Takeaways
name="files[]" and multiple attribute in HTML to upload multiple files.$_FILES['files']['name'] array in PHP to handle each file separately.UPLOAD_ERR_OK before moving files.