Search code examples
phpfilefile-uploadimage-uploadinggetimagesize

How to use getImagesize() for an uploaded file before it gets saved into the server?


Given that getImagesize() requires a string and $_FILES['myfile'] is an array, I've tried to get to the temporary folder and the file uploaded there in order to get the image size, but I do get an error.

This is the error that I get:

Warning: getimagesize(/home/everymorning/public_html/tmp/phpNFuAMD/images.jpeg): failed to open stream: No such file or directory in /home/everymorning/public_html/demo1.php on line 48

And here is what I've tried:

$string = $_SERVER['DOCUMENT_ROOT'].$_FILES['myfile']['tmp_name'].'/'.$_FILES['myfile']['name'];

echo getimagesize($string);

And if I try to use the temporary path directly, I still get an error:

If I use:

getimagesize($_FILES['myfile']['tmp_name']);

I get:

Notice: Array to string conversion in /home/everymorning/public_html/demo1.php on line 47


Solution

  • I think getimagesize($fileName) has following things-

    Array ( [0] => 667 
            [1] => 184 
            [2] => 3 
            [3] => width="667" height="184" 
            [bits] => 8 
            [mime] => image/png );
    

    You are trying to echo an array- error of Array to string conversion. Infact echo could not print array instead print_r and var_dump are the those can print the info of array.

    To calculate the size of an image you can simply calculate by multiplying height width and bits used to represent a pixel and following arithmetic expression can give you size of an image in bits.

     $imageInfo = getimagesize($fileName);
     $size = $imageInfo[0] * $imageInfo[1] * $imageInfo['bits'];