Wednesday, August 02, 2006

[PHP] - [Upload Multiple Images]

[Initial Setup]
1. Create a folder "uploads" on the server
2. Create file.php and upload.php and use the code below


[file.php]
<form enctype="multipart/form-data" action="upload.php" method="post">
Image1: <input name="userfile[]" type="file" /><br />
Image2: <input name="userfile[]" type="file" /><br />
Image3: <input name="userfile[]" type="file" /><br />
Image4: <input name="userfile[]" type="file" /><br />
<input type="submit" value="Upload" />
</form>


[upload.php]
<?php
  $success = 0;
  $fail = 0;
  $uploaddir = 'uploads/';
  for ($i=0;$i<4;$i++)
  {
   if($_FILES['userfile']['name'][$i])
   {
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name'][$i]);
    $ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
    if (preg_match("/(jpg|gif|png|bmp)/",$ext))
    {
     if (move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile))
     {
      $success++;
     }
     else
     {
     echo "Error Uploading the file. Retry after sometime.\n";
     $fail++;
     }
    }
    else
    {
     $fail++;
    }
   }
  }
  echo "<br> Number of files Uploaded:".$success;
  echo "<br> Number of files Failed:".$fail;
?>

Bookmark and Share