Home >Backend Development >PHP Tutorial >How to Upload Multiple Files Using HTML5 and PHP?

How to Upload Multiple Files Using HTML5 and PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 21:43:10546browse

How to Upload Multiple Files Using HTML5 and PHP?

Uploading Multiple Files with HTML and PHP

Q: How can I select and upload multiple files using a single file input control with HTTP POST?

A: In HTML5, this is possible using the following code:

<form method="post" enctype="multipart/form-data">
    <input type="file" name="my_file[]" multiple>
    <input type="submit" value="Upload">
</form>

PHP Code to Handle Upload:

if (isset($_FILES['my_file'])) {
    $myFile = $_FILES['my_file'];
    $fileCount = count($myFile["name"]);

    for ($i = 0; $i < $fileCount; $i++) {
        echo "<p>File #{$i+1}:</p>";
        echo "<p>Name: {$myFile["name"][$i]}<br>";
        echo "Temporary file: {$myFile["tmp_name"][$i]}<br>";
        echo "Type: {$myFile["type"][$i]}<br>";
        echo "Size: {$myFile["size"][$i]}<br>";
        echo "Error: {$myFile["error"][$i]}<br></p>";
    }
}

Example Output:

Suppose two files are selected:

File #1:
Name: image1.jpg
Temporary file: /tmp/phpXXXXXXXX
Type: image/jpeg
Size: 123456
Error: 0

File #2:
Name: image2.jpg
Temporary file: /tmp/phpXXXXXXXX
Type: image/jpeg
Size: 654321
Error: 0

Additional Notes:

  • Use the enctype="multipart/form-data" attribute in the form tag to allow for file uploads.
  • The multiple attribute on the input element enables multiple file selection.
  • Check the PHP manual for proper error handling and secure file upload practices.

The above is the detailed content of How to Upload Multiple Files Using HTML5 and PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn