0

I want to add images goa.jpg, kerala.jpg, delhi.jpg using input type 'file' as multiple. The below code is working perfectly to insert single image.

Now I want to perform multiple image uploading using for loop but I am not getting the actual code without errors. Any one have any experience with this?

                $file_name=$_FILES["packageimage"]["name"];
                $temp_name=$_FILES["packageimage"]["tmp_name"];
                $imgtype=$_FILES["packageimage"]["type"];   if($imgtype!='image/jpeg'&&$imgtype!='image/jpg'&&$imgtype!='image/gif'&&$imgtype!='image/png'&&$imgtype!='image/bmp')
        {     $msg = "Please upload only Image file";   }
         else{ 
        $ext= GetImageExtension($imgtype);
                $imagename=date("d-m-Y")."--".time().$ext;
                $target_path = "../upload/products/".$imagename;
                move_uploaded_file($temp_name, $target_path);

// query to insert images.

        $query=mysql_query("insert into tbl_products set catid='".$catid."', packageimage='".$imagename."',  add_date=now()");
        if($query)
        {
        $msg="Product Added Successfull";
        }

When I am trying using for loop in above code it stores only first image and display only first image.

halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

3

Please have look you can get all idea about multiple upload http://php.net/manual/en/features.file-upload.multiple.php

See bellow example

<?php 
print_r($_FILES);
?>
<form action="" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

See Result is bellow

Array
(
    [userfile] => Array
        (
            [name] => Array
                (
                    [0] => cancelled booking - PAYG.png
                    [1] => cancelled booking - PAYG.png
                )

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

            [tmp_name] => Array
                (
                    [0] => C:\xampp\tmp\php402A.tmp
                    [1] => C:\xampp\tmp\php402B.tmp
                )

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

            [size] => Array
                (
                    [0] => 99134
                    [1] => 99134
                )

        )

)

For Your question following is foreach

<?php 
foreach ($_FILES['userfile'] as $position => $file){
    print_r($file);

}

?>

When Result for that See Bellow :

Array
(
    [0] => cancelled booking - PAYG.png
    [1] => cancelled booking - PAYG.png
)
Array
(
    [0] => image/png
    [1] => image/png
)
Array
(
    [0] => C:\xampp\tmp\php284D.tmp
    [1] => C:\xampp\tmp\php284E.tmp
)
Array
(
    [0] => 0
    [1] => 0
)
Array
(
    [0] => 99134
    [1] => 99134
)

So now you can understand

Thanks Pratik

  • When i am trying to create array like below foreach ($_FILES['array_of_files'] as $position => $file) whole code stop working without showing any error – karan kashyap Dec 16 '15 at 11:20
  • Can you perform this function for me .???? its bit urgent i am trying from past 2 hours but dint get the perfect code.?? – karan kashyap Dec 16 '15 at 11:21
  • Please review my note – Pratik Panchal Dec 16 '15 at 11:29
  • when i put that code foreach ($_FILES['packageimage'] as $position => $file_name) got error as "Warning: Maximum number of allowable file uploads has been exceeded in Unknown on line 0" it still upload only one file. – karan kashyap Dec 16 '15 at 11:37
  • Can you check your "max_file_uploads" in your php.ini? Another option is your apache configuration, sometimes fileupload is restricted in there as well. – Patrick Schumacher Dec 16 '15 at 11:58
1

You can use multiple attribute to upload multiple files, like this:

HTML

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" multiple="multiple" name="packageimage[]" />
  <input type="submit" value="Upload" name="submit" />
</form>

PHP

<?php

    if(isset($_POST['submit'])){
        // directory where the files will get uploaded
        $target_dir = "upload" . DIRECTORY_SEPARATOR . "products";

        // count the number of files uploaded
        $num_of_files = count($_FILES["packageimage"]["name"]);

        // loop through each file to upload
        for($i = 0; $i < $num_of_files; ++$i){

            // valid file extensions
            $valid_extensions = array("gif", "png", "jpg", "jpeg", "bmp");

            // get the file extension
            $ext = strtolower(pathinfo($_FILES["packageimage"]["name"][$i],PATHINFO_EXTENSION));

            // now check against permissible extensions
            if(in_array($ext, $valid_extensions)){

                // target file name
                $target_file = $target_dir . DIRECTORY_SEPARATOR . date("d-m-Y") . "--" . time() . "." . $ext;

                // upload file
                if (move_uploaded_file($_FILES["packageimage"]["tmp_name"][$i], $target_file)) {
                    echo "The file ". basename($_FILES["packageimage"]["name"][$i]). " has been uploaded. <br />";

                    // do your database operations here

                } else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }else{
                echo "Please upload only Image file";
            }

        }
    }

?>

Sidenote: In order to provide cross-platform compatibility, you should use PHP's DIRECTORY_SEPARATOR constant to write path strings, e.g. "..".DIRECTORY_SEPARATOR."foo", because the way to do it on Windows would be "..\foo" while on everything else (Linux, UNIX, Mac OS X) it would be "../foo".

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • I used above code and now getting error not even submitting a single value http://alleggless.com/admin/upload.php admin : admin password:admin please go through above link – karan kashyap Dec 16 '15 at 12:11
  • @karankashyap That's because your `$target_file` is wrong. I've updated my answer. Please re-test your application with the updated code. – Rajdeep Paul Dec 16 '15 at 13:10
  • @karankashyap and I should remind you that your mysql query is wrong. That's not how you insert a new row or update an existing row. – Rajdeep Paul Dec 16 '15 at 13:13
  • @karankashyap Is it working now? What else do you want me to send? – Rajdeep Paul Dec 16 '15 at 13:34
  • @karankashyap: we try to discourage people from asking for a whole solution, since it implies the asker has not made the necessary effort themselves. If you are getting paid for this - presumably that is the relationship you have with your client - shouldn't you do the work? – halfer Dec 16 '15 at 18:46
  • @halfer Dear halfer,i was bissy in chat configuration stuff and project was in testing phase and client rechange requirement suddenly.thats why i want full code it could save my time.but dont worry i resolve that problem from above code ??? – karan kashyap Dec 19 '15 at 16:53
  • @karankashyap Please accept the answer if it solved your problem. – Rajdeep Paul Dec 19 '15 at 16:54
  • @karan: for your own benefit, you need to manage your client. That means that if they change the project from the requirements specification, your change control process kicks in. Here you write an addendum to your requirements analysis, decide how it will impact the project, and negotiate new costs and timescales with the client. Otherwise you (and indeed someone here) is working free of charge, to urgent timescales - which is not good for you and not acceptable for readers here. – halfer Dec 19 '15 at 17:13