4 Replies - 29467 Views - Last Post: 09 July 2018 - 03:14 AM

#1 andrewsw   User is online

  • Bouncy!
  • member icon

Reputation: 6563
  • View blog
  • Posts: 26,619
  • Joined: 12-December 12

Multiple file (image) uploads

Posted 17 September 2014 - 06:50 AM

This snippet provides an outline of the steps involved to upload multiple files (in this case, images) to a sub-folder located on the server. I have included a number of comments but you should find a good tutorial as well, that describes the process in detail. Search "php multiple file upload" or similar.

Uploading multiple files :the docs

First, my form:
    // display the upload-form
    echo <<< THEFORM
<form action="{$_SERVER['PHP_SELF']}" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload Your Picture(s)</legend>
<label for="inpFile">Choose your picture(s)</label>
<input type="hidden" id="max_file" name="MAX_FILE_SIZE" value="300000">
<input type="file" id="inpFile" name="inpFile[]" accept="image/*" 
pattern="/\.(gif|jpe?g|png)$/i" MULTIPLE REQUIRED>
<p>Only image files!</p>
<input type="hidden" id="submitted" name="submitted" value="TRUE">
<input type="submit" id="inpSubmit" name="inpSubmit" value="Upload">
</fieldset>
</form>
THEFORM;

You need a subfolder (or subfolders) on your server to save the images to. I create a subfolder for each user, in a folder named uploads, based on a hash of their username:
    $dirname = $usersalt;
    $user_location = "uploads/$dirname/";

    if (!file_exists($user_location)) {
        mkdir("uploads/$dirname", 0777);
        echo "<p>Your pictures' folder was successfully created.</p>";
    }

However you approach this, you need to supply something for $user_location in the following code.
    do if (isset($_POST['submitted'])) {
        // Nesting the if within do..while(FALSE) allows us to use 
        // break to jump out of this whole section.
        if (!$_FILES['inpFile']) {
            echo "<p><b>No picture selected for upload.</b></p>";
            break;
        }

        $the_pics = $_FILES['inpFile']['name'];
        foreach ($the_pics as $key => $value) {
            // $key == integer, $value = submitted filename
            $fname = $value;
            //Check for valid upload - phpsense.com/2007/php-file-uploading/
            if($_FILES['inpFile']['error'][$key] != UPLOAD_ERR_OK) {
                $file_error = $_FILES['inpFile']['error'][$key];
                if ($file_error == UPLOAD_ERR_FORM_SIZE) {
                    echo "<p>$fname: <b>File is too large (max 300k)</b></p>";
                    break;
                } else {
                    echo "<p><b>$fname: Upload file error: $file_error</b></p>";
                    break;
                } 
            }
            //Check for valid upload
            if(!is_uploaded_file($_FILES['inpFile']['tmp_name'][$key])) {
                echo "<p>$fname: <b>Invalid request.</b></p>";
                break;
            }
            // Validate the type JPEG, GIF or PNG
            $allowed = array('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 
                'image/gif', 'images/PNG', 'image/png', 'image/x-png');
            if (!in_array($_FILES['inpFile']['type'][$key], $allowed)) {
                echo "<p>$fname: <b>Invalid file type.</b></p>";
                break;
            }
            // validate the name
            $allowed_extns = array('jpg', 'jpeg', 'gif', 'png');
            $the_name = $_FILES['inpFile']['name'][$key];
            $the_extn = explode('.', strtolower($the_name));
            if (!in_array(end($the_extn), $allowed_extns)) {
                echo "<p>$fname: <b>Invalid file extension.</b></p>";
                break;
            }
            /* function exif_imagetype() doesn't exist - check PHP version!
            if (exif_imagetype($_FILES['inpFile']['tmp_name'][$key]) != IMAGETYPE_GIF) {
                echo "{$_FILES['inpFile']['tmp_name'][$key]} The picture is not a gif";
            }*/

            //Sanitize the filename
            $remove_these = array(' ','`','"','\'','\\','/');
            $newname = str_replace($remove_these, '', $_FILES['inpFile']['name'][$key]);

            //Make the filename unique (I haven't used this)
            //$newname = time().'-'.$newname;

            //Save the uploaded file to another location
            $upload_path = "{$user_location}{$newname}";
            if (file_exists($upload_path)) {
                echo "<p>$fname: <b>You already have a picture with that name.</b></p>";
                break;
            }
            if (move_uploaded_file($_FILES['inpFile']['tmp_name'][$key], $upload_path)) {
                echo "<p>$fname: <b>Your picture has been uploaded!</b></p>";
            } else {
                echo "<p>$fname: <b>There was a problem uploading your picture!</b></p>";
                break;
            }
        }

    } while (FALSE); // enables the use of 'break'

    // Delete the files from their temp locations (in case there was a problem):
    if (isset($_POST['submitted'])) {
        // $the_pics = $_FILES['inpFile']['name']; (already established)
        foreach ($the_pics as $key => $value) {
            if (file_exists($_FILES['inpFile']['tmp_name'][$key]) && 
                    is_file($_FILES['inpFile']['tmp_name'][$key])) {
                unlink($_FILES['inpFile']['tmp_name'][$key]);
            }
        }
    }


Is This A Good Question/Topic? 0
  • +

Replies To: Multiple file (image) uploads

#2 andrewsw   User is online

  • Bouncy!
  • member icon

Reputation: 6563
  • View blog
  • Posts: 26,619
  • Joined: 12-December 12

Re: Multiple file (image) uploads

Posted 17 September 2014 - 07:12 AM

In case it is helpful, here is the code I use to display a user's images:
    $found_an_image = false;
    if ($handle = opendir("uploads/$dirname")) {
        $image_extns = array('jpg', 'jpeg', 'gif', 'png');
        while (false !== ($entry = readdir($handle))) {
            $ext =pathinfo($entry, PATHINFO_EXTENSION);
            if ($ext == '' || $ext == '.' || $ext == '..')
                continue;
            $ext = strtolower($ext);
            if (in_array($ext, $image_extns)) {
                $image_stats = getimagesize($user_location . $entry);
                if ($image_stats == false) {
                    // do nothing - not an image
                } else {
                    echo "<span class=\"sp_imgs\">" .
                    "<img src=\"images/delete.jpg\" width=\"16\" height=\"16\" " .
                    "class=\"imgdel\" title=\"Delete\">" .
                    "<img src=\"{$user_location}{$entry}\" " .
                    "class=\"yourimgs\" width=\"{$image_stats[0]}\" " .
                    "height=\"{$image_stats[1]}\" title=\"{$entry}\"></span>";
                    $found_an_image = true;
                }
            }
        }
        closedir($handle);
        if (!$found_an_image) {
            echo "<p>No pictures to display.</p>";
        }
    } else {
        echo "<p>Could not open your images folder.</p>";
    }

Notice that I also retrieve the image sizes and use this in the html.

[I have a little button that allows users to delete their images, but I'll leave this as an exercise ;) ]

This post has been edited by andrewsw: 17 September 2014 - 07:14 AM

Was This Post Helpful? 0
  • +
  • -

#3 fahidhasan   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 13-June 15

Re: Multiple file (image) uploads

Posted 13 June 2015 - 05:05 AM

nice...
Was This Post Helpful? 0
  • +
  • -

#4 WebGod   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 23-November 15

Re: Multiple file (image) uploads

Posted 23 November 2015 - 08:35 AM

This has been a lot of help! Thank you :smile:
Was This Post Helpful? 0
  • +
  • -

#5 Intellisensetech   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-July 18

Re: Multiple file (image) uploads

Posted 09 July 2018 - 03:14 AM

Thank you for sharing. This helped me a lot.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1