Multiple file upload using jQuery and PHP

This tutorial shows how easy it is to upload multiple files using jQuery and PHP.

I have used jQuery MultiFile Plugin for this purpose.

The input type file should have name in list format like “pic[]” and the class name of the input should be “multi”.


<input type="file" name="pic[]" class="multi" />

Below is the complete code for multiple file upload


<?php
if(isset($_POST['upload']))
{
    $uploaddir = 'uploads/';
    foreach ($_FILES["pic"]["error"] as $key => $error)
    {
        if ($error == UPLOAD_ERR_OK)
        {
            $tmp_name = $_FILES["pic"]["tmp_name"][$key];
            $name = $_FILES["pic"]["name"][$key];
            $uploadfile = $uploaddir . basename($name);

            if (move_uploaded_file($tmp_name, $uploadfile))
            {
                echo "Success: File ".$name." uploaded.<br/>";
            }
            else
            {
                echo "Error: File ".$name." cannot be uploaded.<br/>";
            }
        }
    }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multiple File Upload with jQuery and PHP</title>

<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script src="jquery.MultiFile.js" type="text/javascript" language="javascript"></script>

</head>

<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic[]" class="multi" />
<input type="submit" name="upload" value="Upload" />
</form>
</body>

</html>

For more multi-file upload examples, see:
http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples

Hope it helps. Thanks.