Check image dimensions (height and width) before uploading image using PHP

94,394

Solution 1

You need something that is executed on the client before the actual upload happens.
With (server-side) php you can check the dimension only after the file has been uploaded or with upload hooks maybe while the image is uploaded (from the image file header data).

So your options are flash, maybe html5 with its FileAPI (haven't tested that, maybe that's not doable), java-applet, silverlight, ...

Solution 2

We can do this with temp file easily.

$image_info = getimagesize($_FILES["file_field_name"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];

Solution 3

This is how I solved it.

$test = getimagesize('../bilder/' . $filnamn);
$width = $test[0];
$height = $test[1];

if ($width > 1000 || $height > 1000)
{
echo '<p>iamge is to big';
unlink('../bilder/'.$filnamn);
}

Solution 4

If the file is in the $_FILES array (because it's been selected in a Multipart form), it has already been uploaded to the server (usually to /tmp or similar file path) so you can just go ahead and use the getimagesize() function in php to get the dimensions (including all details as array).

Solution 5

This work for me

$file = $_FILES["files"]['tmp_name'];
list($width, $height) = getimagesize($file);

if($width > "180" || $height > "70") {
    echo "Error : image size must be 180 x 70 pixels.";
    exit;
}
Share:
94,394
Hakan
Author by

Hakan

Updated on July 01, 2020

Comments

  • Hakan
    Hakan almost 4 years

    How can I check for height and width before uploading image, using PHP.

    Must I upload the image first and use "getimagesize()"? Or can I check this before uploading it using PHP?

    <?php
    
    foreach ($_FILES["files"]["error"] as $key => $error) {
    if(
    $error == UPLOAD_ERR_OK
    && $_FILES["files"]["size"][$key] < 500000 
    && $_FILES["files"]["type"][$key] == "image/gif"
    || $_FILES["files"]["type"][$key] == "image/png"
    || $_FILES["files"]["type"][$key] == "image/jpeg"
    || $_FILES["files"]["type"][$key] == "image/pjpeg" 
    ){
    
    
    $filename = $_FILES["files"]["name"][$key];
    
    
    
    
    
    
    
    
    if(HOW TO CHECK WIDTH AND HEIGHT)
    {
    echo '<p>image dimenssions must be less than 1000px width and 1000px height';
    }
    
    
    }
    
    
    
    
    
    
    
    ?>