Error with getimagesize when uploading photo

0

I'm trying to mount a system that checks the mime type of the image when uploading. But it is giving an error.

Follow the code:

<?php 

$action = addslashes(filter_input(INPUT_GET, 'action',FILTER_SANITIZE_SPECIAL_CHARS));

if ((!empty($action)) and ($action == "add")) {
   // Recebe a imagem 
   $imagem = $_FILES["imagem"];

   $size = getimagesize($imagem); 

   switch ($size['mime']) { 
       case "image/gif": 
           echo "Image is a gif"; 
           break; 
       case "image/jpeg": 
           echo "Image is a jpeg"; 
           break; 
       case "image/png": 
           echo "Image is a png"; 
           break; 
       case "image/bmp": 
           echo "Image is a bmp"; 
           break; 
   } 
}

?>

<form name='form' method='post' action='?action=add' enctype='multipart/form-data'>
    <input type="file" name="imagem">
    <input type="submit" value="ok">
</form>

Error log:

  

Warning: getimagesize () expects parameter 1 to be string, array given in /Library/WebServer/Documents/teste.php on line 12

The error occurs on this line:

$size = getimagesize($imagem); 

Modified to

$ image = $ _FILES ['image'] ['tmp_name'];

But returns error in getimagesize() . "Parameter can not be empty"

    
asked by anonymous 21.10.2016 / 13:25

1 answer

1

In this excerpt from the original code,

$imagem = $_FILES["imagem"];

Modify to

$imagem = $_FILES['imagem']['tmp_name'];

The above example is considering an image only. To upload multiple images you need a different treatment.

If you have questions about what the array indexes are, make a print_r($_FILES); exit; . Then you can see the structure.

To give more consistency to switch()

 case "image/jpeg": 
       echo "Image is a jpeg"; 
       break;

Switch to

 case "image/jpeg":
 case "image/pjpeg":
 case "image/jpg":
 case "image/pjpg":
       echo "Image is a jpeg"; 
       break; 

The reason is that jpg can come with one of these 4 formats.

Another point that needs to be more consistent is to check if the image exists before attempting to use it.

if (file_exists($imagem)) {
    $size = getimagesize($imagem); 
} else {
    // dispara um exception, seta um código de erro.. enfim, o que vc preferir
}

There are many other details. I just showed the most obvious and simple.

The examples are merely didactic.

    
21.10.2016 / 15:50