OzzC
OzzC

Reputation: 821

Im having some errors, trying to upload multiple images

Im trying to upload, for the first time, not only 1 image, but multiple.

Im trying with this code below:

My input:

<input type="file"  name="img[]" size="60" multiple="multiple"  accept="image/*" />

My code to upload:

$folder= '../images/';  
$year= date('Y');
$month= date('m');


if($_FILES['img']['tmp_name'])
{
   $count = count($_FILES['img']['tmp_name']);
   $img = $_FILES['img'];

   for($i=0;$i<=$count;$i++)
   {
    $ext = substr($img['name'][$i],-3);
    $image = $img['name'];
    $extAlllowed = array('image/jpeg','image/pjpeg','image/png','image/gif');

    if(in_array($img['type'][$i],$extAlllowed))
    {
       uploadImage($img['tmp_name'][$i],$image,'800',$folder.$year.'/'.$month.'/');
    }   
   }
}

But Im having some errors, but the two more important are this:

substr() expects parameter 1 to be string, array given in $ext = substr($name,-3);

Notice: Undefined variable: img in $x = imagesx($img);

My function to upload is this, I never used it for multiple uploads, but it should work with the for loop:

function uploadImage($tmp, $name, $width, $folder){
        $ext = substr($name,-3);

        switch($ext){
            case 'jpg': $img = imagecreatefromjpeg($tmp); break;
            case 'png': $img = imagecreatefrompng($tmp); break;
            case 'gif': $img = imagecreatefromgif($tmp); break; 
        }       
        $x = imagesx($img);
        $y = imagesy($img);
        $height = ($width*$y) / $x;
        $new_image   = imagecreatetruecolor($width, $height);

        imagealphablending($new_image,false);
        imagesavealpha($new_image,true);
        imagecopyresampled($new_image, $img, 0, 0, 0, 0, $width, $height, $x, $y);

        switch($ext){
            case 'jpg': imagejpeg($new_image, $folder.$name, 100); break;
            case 'png': imagepng($new_image, $folder.$name); break;
            case 'gif': imagegif($new_image, $folder.$name); break; 
        }
        imagedestroy($img);
        imagedestroy($new_image);
    }

Upvotes: 0

Views: 48

Answers (1)

broch
broch

Reputation: 433

Try to to printout the $_FILES with the print_r($_FILES); function. The structure of $_FILES changes with multiple files and maybe that is your problem

And your line for($i=0;$i<=$count;$i++) should be:

for($i=0;$i<$count;$i++)

Upvotes: 1

Related Questions