How can I select and upload multiple files with HTML and PHP, using HTTP POST?
You can use the following HTML code to create a form that allows users to select and upload multiple files:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select files to upload:
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
The enctype
attribute specifies that the form will be sent as multipart/form-data, which is the encoding required for file uploads. The multiple
attribute of the input
element allows the user to select multiple files at once.
Then, in your PHP code, you can access the uploaded files using the $_FILES
superglobal array. Here's an example of how you can handle the file uploads in PHP:
<?php
$uploaded_files = $_FILES['files'];
foreach ($uploaded_files['name'] as $key => $name) {
$tmp_name = $uploaded_files['tmp_name'][$key];
$error = $uploaded_files['error'][$key];
$size = $uploaded_files['size'][$key];
// Check for errors
if ($error == UPLOAD_ERR_OK) {
// Move the uploaded file to the desired location
move_uploaded_file($tmp_name, "uploads/$name");
}
}
?>
This code iterates over the uploaded files and checks for any errors. If there are no errors, it moves the uploaded file to the uploads
directory using the move_uploaded_file
function.
We hope this helps! Let us know if you have any questions.