Explain Codes LogoExplain Codes Logo

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

html
file-upload
http-post
php
Anton ShumikhinbyAnton Shumikhin·Nov 17, 2024
TLDR

Enable multiple file uploads in HTML by using the multiple attribute on an <input>, then process those files server-side with PHP using the $_FILES global variable.

HTML:

<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="files[]" id="file" multiple> <input type="submit" value="Upload Files" name="submit"> </form>

PHP:

if (isset($_FILES['files'])) { foreach ($_FILES['files']['tmp_name'] as $index => $tmpName) { $filename = basename($_FILES['files']['name'][$index]); $uploadPath = "uploads/" . $filename; // In case of filename collision, double park it with a stylish suffix if (file_exists($uploadPath)) { $uploadPath = "uploads/" . uniqid() . "_" . $filename; } if (move_uploaded_file($tmpName, $uploadPath)) { echo "File Uber arrived successfully: " . $uploadPath . "<br>"; } else { echo "Lost in transit: " . $filename . "<br>"; } } }

Remember to check your php.ini settings for upload_max_filesize and max_file_uploads to ensure your PHP installation doesn't get overwhelmed by really enthusiastic users.

Itemized Breakdown

HTML File Input

When working with multiple file uploads, format the name attribute as an array:

<input type="file" name="files[]" id="file" multiple>

Resolving Clashing Filenames

Verify that any given filename does not already exist in the directory by using file_exists(). If a conflict arises, you can use uniqid() to append a unique suffix to the filename.

Security Protocols

Support both file type and size checks to prevent your server from unwanted uploads. These checks should be performed before processing the files.

File Transfer

We use move_uploaded_file() to safely relocate the files to their designated upload directory, inside a foreach loop to handle each file individually.

File Upload Progress Report

An echo informs the user about each file's transfer, whether successful or not.

"But, Wait! There's More!" Section

Hall Monitor on Duty

Ensure that the directory where you store your uploaded files is both securely permissioned and, preferably, outside of your website's root directory.

Just a Moment, Please...

Incorporate progress bars or loaders to enhance your users' upload experiences. You can achieve this client-side with JavaScript, or use AJAX with FormData.

Hulk-Sized Files

Adjust your php.ini settings to effectively manage large file uploads. Turn up your memory_limit and max_execution_time when necessary, and keep a watchful eye on your error_log for any unexpected PHP errors encountered during the upload process.