Blog
Multiple File Upload in PHP: Form, Validation and Demo
To upload multiple files in PHP, create a POST form with enctype="multipart/form-data" and an input using name="files[]" and multiple. PHP groups the uploads in $_FILES['files']; validate each file before moving it into private storage.
This tutorial provides the form, explains the upload arrays, and includes a complete downloadable PHP project. Try the browser selection preview first, then run the PHP form on localhost to test real uploads.
Multiple file upload in PHP: quick reference
| Part | Purpose |
|---|---|
method="post" |
Sends the upload request to PHP. |
multipart/form-data |
Includes file data in the request body. |
name="files[]" multiple |
Allows a selection and organizes file metadata as arrays. |
$_FILES['files']['tmp_name'][$i] |
Identifies a temporary uploaded file. |
move_uploaded_file() |
Moves a valid PHP HTTP upload to the chosen destination. |
PHP documents the array structure in its multiple-file upload guide and the form requirements in its POST upload guide.
Live demo: preview a file selection
This embedded demo checks selection metadata locally. It does not submit files to SanWebCorner. The downloadable project contains the actual PHP upload form and server handler.
Preview a multiple-file selection
Choose JPG, PNG, or PDF files to check filenames, count, and size in your browser. This preview does not upload or read file contents.
Up to 5 files · 2 MiB per file · 10 MiB total. Selecting again replaces the previous selection.
Ready. Choose your own files or try sample metadata.
Browser checks use metadata only. The downloadable PHP project repeats validation on the server and inspects detected MIME types before storing uploads.
Enable JavaScript for this local preview. The downloadable PHP form works without JavaScript.
1. Create the HTML upload form
Give the input an array-style name and enable multiple selection. The accept attribute makes the picker more convenient, but a server must independently validate received files.
<form action="index.php" method="post" enctype="multipart/form-data">
<!-- Render a session CSRF token here; included in the full project. -->
<label for="files">Choose JPG, PNG, or PDF files</label>
<input id="files" name="files[]" type="file"
accept=".jpg,.jpeg,.png,.pdf" multiple required>
<button type="submit">Upload selected files</button>
</form>
The ZIP adds a session token to this form, then handles the POST in public/index.php. The PHP form works without JavaScript; the browser preview is separate.
2. Understand the PHP upload arrays
A multiple-file input produces parallel arrays. For index $i, use name for the supplied filename, tmp_name for the temporary path, error for the upload result, and size for the reported byte count. The supplied type is browser metadata, so do not treat it as a trusted file-content check.
// Structural example only: validate the request before processing.
foreach ($_FILES['files']['name'] as $i => $originalName) {
$temporaryPath = $_FILES['files']['tmp_name'][$i];
$uploadError = $_FILES['files']['error'][$i];
// Validate error, actual size, extension and detected MIME here.
// Move only after the full batch passes the checks.
}
Validate the array shape too. A malformed request can contain nested arrays or missing keys. The downloadable handler rejects those requests rather than assuming every field is a string or integer.
3. Validate uploads before storing them
| Rule in this example | Server behavior |
|---|---|
| Count | Accept 1–5 files. |
| Size | Require non-empty files up to 2 MiB each and 10 MiB total. |
| Upload result | Require UPLOAD_ERR_OK and a valid HTTP upload. |
| Allowed content | Require JPG/JPEG, PNG, or PDF extension matching the detected MIME; inspect image headers for images. |
| Storage | Use random filenames outside the served public/ directory. |
| Form token | Compare the submitted token with the session token. |
Use PHP’s Fileinfo MIME detection to inspect the temporary file. Extension and MIME matching provide useful checks but cannot establish that a document is harmless. The project validates the entire batch before attempting file moves.
// Excerpt: the complete request checks are in public/index.php.
$mime = new finfo(FILEINFO_MIME_TYPE);
$detected = $mime->file($temporaryPath);
$allowed = ['jpg' => 'image/jpeg', 'png' => 'image/png',
'pdf' => 'application/pdf'];
// Do not use the original filename as the destination.
$destination = $privateDirectory . DIRECTORY_SEPARATOR
. bin2hex(random_bytes(24)) . '.' . $validatedExtension;
if (!move_uploaded_file($temporaryPath, $destination)) {
throw new RuntimeException('Could not store the upload.');
}
The excerpt is explanatory, not a standalone handler. The full project supports .jpeg as well, checks all request fields, and handles failed moves. PHP’s move_uploaded_file() reference explains its HTTP-upload verification and destination behavior.
4. Run the downloadable PHP project
Extract the ZIP. Use a supported PHP 8.x installation with sessions and Fileinfo enabled. In the extracted multiple-file-upload-demo directory, run:
php -d file_uploads=1 -d upload_max_filesize=2M -d post_max_size=16M -d max_file_uploads=20 -S 127.0.0.1:8080 -t public
Open http://127.0.0.1:8080/index.php and select two small test files. Successful uploads are saved in storage/ beside public/. Serve only public/; the built-in server is for local development. Stop it with Ctrl+C. On Windows, enable Fileinfo in the active PHP configuration if php -m does not list it.
multiple-file-upload-demo/
├── public/
│ ├── index.php # Real PHP upload form and handler
│ ├── preview.html # Local-only selection preview
│ ├── preview.js
│ └── style.css
├── php-demo.ini # Example limit settings
├── README.md
└── storage/ # Created on the first valid upload, outside public/
There is no public download endpoint for uploaded files. The project stores files locally and does not send email. Remove your own test uploads from storage/ when finished.
5. Configure PHP limits and handle errors
upload_max_filesize limits an individual file; post_max_size limits the entire request, including multipart overhead. Leave the POST limit above the combined permitted payload. Keep max_file_uploads above your application count limit so PHP does not truncate a normal oversized selection before your code can reject it.
| Symptom | What to check |
|---|---|
$_FILES is empty |
Confirm multipart encoding, input name, POST size limit, and server request limits. |
| PHP upload error 1 or 2 | Check PHP/form size limits; the handler still enforces its own byte limit. |
| PHP upload error 3 or 4 | Retry a partial upload or select a file. |
| Fileinfo is unavailable | Enable the extension in your active PHP installation. |
| File cannot be stored | Check the destination directory’s permissions and free disk space. |
| Renamed file is rejected | Its detected MIME does not match its allowed extension. |
See PHP’s upload error codes. Very large requests may be rejected by the web server before this handler runs. If PHP discards an oversized POST body, the project reports an invalid token/request-size error because form fields are missing.
How to adapt this example for a public website
Add authenticated access, authorization, rate limits, per-user quotas, storage monitoring, retention cleanup, and content scanning appropriate to your files. Keep uploads private and use a controlled retrieval handler if downloads are needed. A MIME or image-header check alone is insufficient for public upload security. Review the OWASP File Upload Cheat Sheet when designing the deployed flow.
If your contact form also needs email attachments, validate uploads first and integrate a maintained mail library with credentials in server configuration. The legacy mail-send code is replaced here by a focused upload example; no SMTP credentials or email delivery are included.
Frequently asked questions
Can PHP upload multiple files without JavaScript?
Yes. An HTML multipart POST form with a multiple file input is sufficient. JavaScript is optional for previews, progress displays, and asynchronous requests.
Why do I need square brackets in files[]?
The array-style name tells PHP to organize the multiple uploaded files under the same field as parallel arrays. Use the same field name when reading $_FILES.
Does the live demo upload files to SanWebCorner?
No. It checks local selection metadata only. Run the included PHP project on localhost to test real server uploads.
Is the HTML accept attribute enough to validate a file?
No. It is a file-picker hint. The server must check upload errors, size, allowed extensions, detected content types, and storage rules independently.
Can I keep the original filenames?
Store an escaped display name separately if your application needs it. Use generated storage names to avoid collisions and prevent user-supplied names from defining filesystem paths.
Can I increase the number or size of files?
Yes. Update the browser rules, server constants, PHP limits, request limits, and storage quotas together. Allow enough request-body overhead and test the new limits.
Build and test the complete upload flow
Use the preview to explore file-selection behavior, then test the PHP handler with valid files, empty files, oversized files, wrong extensions, and duplicate names. The ZIP contains the complete form, validation logic, styles, local preview, and setup guide.