Solved

uploading multiple image with php

Posted on 2016-11-20
14
20 Views
Last Modified: 2016-11-21
I need to let my users to upload multiple images to my web site,

do you have the code for uploading multiple image with php?

I don't show error messages on my page for the security risk, they are off by default.
0
Comment
Question by:Braveheartli
  • 7
  • 5
  • 2
14 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41895459
Images are uploaded in the $_FILES array.

Assuming you are uploading your files with standard HTML file inputs there are two approaches
Approach 1 - you name each file input
<input type="file" name="image1" />
<input type="file" name="image2" />

Open in new window

This will result in a $_FILES array that looks like this
Array
(
    [image1] => Array
        (
            [name] => background5.jpg
            [type] => image/jpeg
            [tmp_name] => C:\Windows\Temp\php4C53.tmp
            [error] => 0
            [size] => 309187
        )

    [image2] => Array
        (
            [name] => eetest.jpg
            [type] => image/jpeg
            [tmp_name] => C:\Windows\Temp\php4C54.tmp
            [error] => 0
            [size] => 47336
        )
)

Open in new window

Approach 2 - use the multiple attribute on the <input> control. This allows you to select multiple files and assign them to a single <input>
<input name="file[]" type="file" multiple /> 

Open in new window

This will result in a $_FILES array that looks like this
Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => background2.jpg
                    [1] => background3.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => C:\Windows\Temp\php6B9E.tmp
                    [1] => C:\Windows\Temp\php6B9F.tmp
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 8989
                    [1] => 6172
                )

        )
)

Open in new window


Use the first approach when you want to request specific images for a specific purpose - the named inputs allows you to map the image to its purpose.
The second approach is if you are providing something like a gallery - there can be any number of images in any order.

Assuming you go with Approach 1. Then you would need PHP code that processes the first $_FILES array

foreach($_FILES as $file) {
   // Change path if you want to use a specific name
   $dest = "/path/to/images/" . $file['name'];
   uploadFile($file, $dest);
}

function uploadFile($file, $destination, $mimetypes=false, $size = 0) 
{
   // check that the file is within the required parameters
   // Check size, mimetype here
   if ($size > 0 && filesize($file['tmp_name']) > $size) {
      return false;
   }
   if (is_array($mimetypes)) {
      $exif = exif_imagetype($file['tmp_name'];
      $valid = false;
      foreach($mimetypes as $type) {
         if ($exif === $type) {
            $valid = true;
            break;
         }
      }
   }
   if (!$valid) {
      return false;
   }
   // file is valid
   return move_uploaded_file($file['tmp_name'], $destination);
}

Open in new window

0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41895468
Dear Julian,
thank you, As you guest, I prefer the first approach.

Do you have complete code or sample for this?

I need to let my users upload only jpeg and .gif files and I need to limit the file size.
do you have complete code for this?
0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41895566
Let me try it please.
I will let you know after i try it. Thank you
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41895573
The code above is complete you need to adapt to your particular setup - for instance how do the files get named - do you decide that or do your users decide?
Where are the files saved to?
What are you calling your input's?

If you want to limit size on the PHP side then you would do something like
Assume inputs are file1 and file2
$maxsize = 1024*1024*2; // 2 MB
$types = array(IMAGETYPE_JPEG, IMAGETYPE_GIF);
if (!empty($_FILES['file1])) {
  $destination = '/path/to/uploaded/file.jpg';
  if (!uploadFile($_FILES['file1'], $destination, $types,$size)) {
    // handle error here
  }
}
if (!empty($_FILES['file2'])) {
  $destination = '/path/to/uploaded/file.gif';
  if (!uploadFile($_FILES['file2'], $destination, $types,$size)) {
    // handle error here
  }
}

Open in new window


To supply more code than that I would require details of how you are processing the user response. Are there other form fields, how do you want to deal with errors, where do you store the images, do you need to store a reference to the images in a DB.

Here is a working sample based on the code above. Source for the sample is available on the sample page.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41895661
This is my teaching example showing how to use HTML5 to send a multiple-file upload to your server.
<?php // demo/upload_multiple_html5_example.php
/**
 * This script demonstrates the HTML5 document that you need to use
 * for multiple file uploads.  The "action=" script would be in a
 * separate document.
 */
error_reporting(E_ALL);


/**
 * Activate these lines to see the request variables
 *
var_dump($_POST);
var_dump($_FILES);
 *
 */

// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
/* JQUERY CODE HERE */
});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<form enctype="multipart/form-data" method="post">
<input type="file" multiple name="my_files[]" />
<input type="submit" />
</form>

</body>
</html>
HTML5;


// RENDER THE WEB PAGE
echo $htm;

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41895666
And here is a little more elaborate example showing how to process the file uploads, after they are received by the server.  It covers the common upload errors, questions related to overwriting files, etc.  There are a number of man page references called out in the comments.  These are worth your time to read them.
<?php // demo/upload_example.php
/**
 * Demonstrate how to upload one or more files, using HTML5 and PHP
 *
 * REQUIRED: Man Page References
 * http://www.w3schools.com/tags/att_input_multiple.asp
 *
 * http://php.net/manual/en/reserved.variables.files.php
 * http://php.net/manual/en/features.file-upload.php
 * http://php.net/manual/en/features.file-upload.post-method.php
 * http://php.net/manual/en/features.file-upload.common-pitfalls.php
 * http://php.net/manual/en/features.file-upload.errors.php
 * http://php.net/manual/en/features.file-upload.multiple.php
 *
 * http://php.net/manual/en/function.move-uploaded-file.php
 *
 * IMPORTANT: If dealing with large files
 * http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
 * http://php.net/manual/en/ini.core.php#ini.post-max-size
 * http://php.net/manual/en/info.configuration.php#ini.max-input-time
 */
error_reporting(E_ALL);

// MAY NOT BE NEEDED - CHECK PHP_INI PARAMETERS FOR YOUR TIMEZONE
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('storage' DIRECTORY)
$storage = 'storage';
if (!is_dir($storage))
{
    mkdir($storage);
}

// ESTABLISH THE BIGGEST FILE SIZE WE WILL ACCEPT - ABOUT 8 MB
$max_file_size = 8 * 1024 * 1024;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WILL ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'doc'
, 'docx'
)
;

// ARRAY OF ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( UPLOAD_ERR_OK         => "Success!"
, UPLOAD_ERR_INI_SIZE   => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, UPLOAD_ERR_FORM_SIZE  => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, UPLOAD_ERR_PARTIAL    => "The uploaded file was only partially uploaded"
, UPLOAD_ERR_NO_FILE    => "No file was uploaded"
, 5                     => "UNDEFINED ERROR #5"
, UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder"
, UPLOAD_ERR_CANT_WRITE => "Cannot write file to disk"
, UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the file upload"
)
;


// IF WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
if (!empty($_POST))
{
    echo "<h2>Results: File Upload</h2>" . PHP_EOL;

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH IN THE REQUEST
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>";

    // REORGANIZE THE CONTENTS OF $_FILES SO WE CAN USE AN ITERATOR MORE SENSIBLY
    $nf = count($_FILES['userfile']['name']);
    while ($nf)
    {
        $nf--;
        $my_uploaded_files[$nf]['name']     = $_FILES['userfile']['name'][$nf];
        $my_uploaded_files[$nf]['type']     = $_FILES['userfile']['type'][$nf];
        $my_uploaded_files[$nf]['tmp_name'] = $_FILES['userfile']['tmp_name'][$nf];
        $my_uploaded_files[$nf]['error']    = $_FILES['userfile']['error'][$nf];
        $my_uploaded_files[$nf]['size']     = $_FILES['userfile']['size'][$nf];
    }

    // ITERATE OVER THE COLLECTION OF UPLOADED FILES
    foreach ($my_uploaded_files as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == UPLOAD_ERR_NO_FILE) continue;

        // IF THERE ARE ERRORS
        if ($error_code != UPLOAD_ERR_OK)
        {
            $error_message = $errors[$error_code];
            trigger_error("Upload error code: $error_code: $error_message", E_USER_WARNING);
            continue;
        }

        // SYNTHESIZE THE NEW FILE NAME
        $f_type = explode('.', basename($my_uploaded_file['name']));
        $f_type = end($f_type);
        $f_type = trim(strtolower($f_type));

        $f_name = explode('.', basename($my_uploaded_file['name']));
        $f_name = current($f_name);
        $f_name = trim(strtolower($f_name));

        // SERVER PATH TO THE NEW FILE
        $my_file_path
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $storage
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // URL PATH TO THE NEW FILE
        $my_file_url
        = $storage
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts))
        {
            trigger_error("$f_type Not allowed", E_USER_WARNING);
            continue;
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_file_path))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file_url</i></b> already exists." . PHP_EOL;

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d\THis');
                $my_bak = $my_file_path . '.' . $now . '.bak';
                if (!copy($my_file_path, $my_bak))
                {
                    trigger_error("Backup Failed for $my_file_url", E_USER_WARNING);
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten." . PHP_EOL; }
        if ($upload_success == 1) { echo "<br/><b>$my_file_url</b> has been saved." . PHP_EOL; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>" . PHP_EOL; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR: $my_file_url NOT SAVED - SEE WARNING FROM <i>move_uploaded_file()</i></b>" . PHP_EOL; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded." . PHP_EOL;
            if (!chmod ($my_file_path, 0755))
            {
                echo '<br/>chmod(0755) FAILED: fileperms() = ';
                echo substr(sprintf('%o', fileperms($my_file_path)), -4);
            }
            echo '<br/>See the file: <a target="_blank" href="' . $my_file_url . '">' . $my_file_url . '</a><br/>' . PHP_EOL;
        }
    } // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
} // END ACTION SCRIPT


// CREATE THE HTML FORM USING HEREDOC NOTATION
$form = <<<EOF
<h2>Upload file(s)</h2>
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    REQUIRES THE HTML5 DOCTYPE
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>

<input type="file" multiple name="userfile[]" size="80" />

<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
<input type="submit" value="Upload" />
</form>
EOF;

echo $form;

Open in new window

0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41895687
Dear Ray,
thank you very very much.

Dear Julian Hansen, I thank you too. Somehow, I couldn't upload files with your code. I'm sure it's my fault.

But Ray's code works, perfectly fine.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 1

Author Comment

by:Braveheartli
ID: 41895735
Dear Ray Paseur,
I use your code, I can see what I uploaded on the page.

echo '<br/>See the file: <a target="_blank" href="' . $my_file_url . '">' . $my_file_url . '</a><br/>' . PHP_EOL;

Since it's more than one picture, how can I insert the link into my database?

I think I can insert the link into database inside the foreach loop that you use to print out the link on the page.

if I do this, would it work inside the foreach loop?

$sql = "INSERT INTO ilan (uid,imageurl) VALUES ('$uid','$my_file_url');"
but there is more than one image url? How can I do this?

Normally I insert all the data in one row whit where clause. ( Where uid='$uid'; )
Should I create a lookup table to insert the picture urls?
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41895759
0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41895761
Dear Julian,
Yes, I tried. Unfortunately, I couldn't make it work
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41895799
That might be a bandwidth thing .

The sample requires that the first image is a JPEG and the second is a GIF
See screenshot below
-ss94.jpg
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41895802
Just checking in this post you said
thank you, As you guest, I prefer the first approach.

Ray's solution uses a single input with the multiple attribute - which was the second approach I suggested.

Which one are you wanting to use the first (individual inputs) or the second (single input with multiple attribute)?
0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41895813
Dear Julian,
I somehow manage it. Ray's code is working and I do not have deep knowledge about programming. I'm sure yours is working too.
I will use Ray's code for now. But I have to work on it.

I inserted the link of the pictures to my database, so that everything seems fine now. I will split the points.
0
 
LVL 1

Author Closing Comment

by:Braveheartli
ID: 41895814
thank you both.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Wordpress Query 1 35
WooCommerce Sort by Date 4 11
mysql Encryption with PHP 8 51
Adding Extra Information box 4 26
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now