• Home
  • Shell
    • Emacs
    • Perl
    • screen
    • sed
  • Ubuntu
    • VNC
  • Web Development
    • Javascript
    • Joomla
    • MySQL
    • osTicket
  • Windows
    • Gimp

Web Dev> Allow users to upload multiple files

Apr12
2011
Written by Scott Rowley

In this particular example we are allowing users to upload up to 4 image files at a time (we will specify jpeg, jpg, gif, png, and bmp to be allowed). We will also restrict the size to less than 2mb (16777216 bits)

First we need the page containing our form for uploading the files:

file.php

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

Now we need the file that will actually do all the work:

upload.php

<?php
$success = 0;
$fail = 0;
$uploaddir = 'images/';
for ($i=0;$i<4;$i++)
{
if($_FILES['file']['name'][$i])
{
// Allow only up to 2mb images
if($_FILES['file']['size'][$i] < 16777216){
$uploadfile = $uploaddir . basename($_FILES['file']['name'][$i]);
$ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
if (preg_match("/(jpeg|jpg|gif|png|bmp)/",$ext))
{
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadfile))
{
echo " http://example.com/" . $uploadfile . "<br>";
$success++;
}
else
{
echo "Error Uploading the file. Retry after sometime.\n";
$fail++;
}
}
else
{
$fail++;
}
}else{echo "Error uploading file, file is too large";
$fail++;}
}
}
if($success > 0){
echo "<br>Number of files successfully uploaded: " . $success;
}else{
echo "<br>Number of files failed: " . $fail;
}
?>
Posted in Web Development
« Web Dev> HTML form ‘Back’ button
» Web Dev> Meta-Redirect

Corrections? Questions? Comments?

Find an error?
Everything work out great for you?
Have some feedback?
Like to see something added to the article?

PLEASE leave us a comment after the article and let us know how we are doing, or if something needs corrected, improved or clarified.

Thank you!
- The Management

Advertisement

Sudo Bash
By Geeks - For Geeks

Back to Top