Tiffany B. Brown

29 March 2011

Quick PHP Tip: Uploading multiple files in HTML5

One of the neat things about HTML5 is that it allows for multiple file uploads in one file upload field. Of course, you have to have a browser that supports such a feature. Currently Opera 11.10 does. So do Firefox 4, the latest version of Chrome, and Safari 5.0.4. (Internet Explorer 9 does not.)

Now what's less clear is how to send data from multiple files to a server-side PHP script. Turns out, it's quite easy. Treat it in the same way you'd treat any other array of options (radio buttons, for example) and include square ([]) brackets in the field name. See the code below for an example:

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="UTF-8">
    <title>HTML5 Multiple File Upload</title>
    <link rel="stylesheet" href="s.css" media="screen">
    <style media="screen"></style>
</head>
<body>
    <form action="processor.php" method="post" enctype="multipart/form-data">
        <input type="file" value="" name="upload[]" multiple>
        <button type="submit">Upload!</button>
    </form>
<script></script>
</body>
</html>

In processor.php, all we're going to do is print the $_FILES array so you can see what's happening.

<pre>
<?php
     print_r( $_FILES );
?>
</pre>

Copy and paste this code and save it to your own server to see everything in action.

Related: