Pages

Friday, November 19, 2010

Multiple files upload with a single form

Uploading multiple files is a easy thing do with php.
Follow these steps to upload multiple files(images)

Steps:
1. Create two files index.php and upload.php

2. Copy this to index.php
<!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=iso-8859-1" />
<title>File Upload</title>
</head>
<body>
<form name="upload" id="upload" method="post" action="upload.php" enctype="multipart/form-data">
  <?php
    for($i=0; $i<10; $i++)  
   {
          echo "<b>File ".($i+1).":</b> &nbsp;";
    ?>
          <input type="file" name="fileupload[]"  />
          <br />
  <?php
    }
  ?>
  <input type="submit" name="upload_submit" value="Upload My Files" />
</form>
</body>
</html>


3. Copy this to upload.php
<?php

$max_file_size = ((2) * (1024) * (1024));//upload upto 2 mega bytes
$destination_path   = "C:/uploads/";

if(!empty($_FILES['fileupload']))
{
    for($i=0; $i<10; $i++)
    {
        if(is_uploaded_file($_FILES['fileupload']['tmp_name'][$i]))
        {
            if($max_file_size<$_FILES['fileupload']['size'][$i])
            {
                echo $_FILES['fileupload']['name'][$i] . " is exceeded the upload limit.<br />";
                continue;
            }
            else
            {
                if(preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['fileupload']['name'][$i]))
                {
                    echo $_FILES['fileupload']['name'][$i] . " is not allowed to upload.<br />";
                    continue;
                }
                else
                {
                    $upload            = false;
                    $source         = $_FILES['fileupload']['tmp_name'][$i];
                    $destination    = $destination_path . $_FILES['fileupload']['name'][$i];
                    $upload            = move_uploaded_file($source,$destination);
                   
                    if($upload)
                        echo $_FILES['fileupload']['name'][$i] . " is uploaded successfully.<br />";
                }
            }
        }
   
    }

}
echo '<br /><br /><a href="javascript:history.go(-1)">Back</a>';
?>


4. Create C:/uploads folder or replace the destination_path value in upload.php

5. Thats all. You have completed the file uploads in a minutes.

If you have any questions in this script or need new script, feel free to post your questions here.

1 comment: