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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Checking Image Dimensions Without Uploading

You do not need to upload an image just to check its dimensions. The standard approach of calling getimagesize() immediately after moving a file to disk is functional but inefficient if your validation logic requires strict dimension limits. You can inspect the metadata provided directly by the HTTP client before any file system interaction occurs.

The PHP SAPI ($_FILES) superglobal contains a specific entry: $_FILES["files"]["tmp_name"]. This property holds the path to the temporary file created by the upload handler, but it also includes $_FILES["files"]["size"] and $_FILES["files"]["type"]. However, these properties are insufficient for checking width and height. The client does not send dimension metadata in the standard multipart form data headers; that information is embedded within the binary content of the file itself.

To validate dimensions without writing the file to your permanent storage or even its temporary directory if you reject it immediately, you must read the file pointer opened by $_FILES["files"]["tmp_name"]. This allows you to parse the header bytes of the image format (JPEG, PNG, GIF) to extract the EXIF tag or the IDAT/IHDR chunks.

Reading Dimensions from Temporary Files

The most reliable way to achieve this is by using exif_read_data() or by manually parsing the binary stream depending on your requirements. If you are dealing with JPEG files, exif_read_data() will often return the image width and height if the EXIF data was embedded during capture. For PNG and GIF, you generally need to parse the file header manually because they do not store dimensions in an EXIF tag.

Here is a practical implementation using imagecreatefrom... functions wrapped in a validation check. This method loads the image into memory only for reading, without moving it:

$allowedTypes = ['image/gif', 'image/png', 'image/jpeg', 'image/pjpeg'];
$maxWidth = 1000;
$maxHeight = 1000;
$maxSize = 500000; // 500KB

foreach ($_FILES["files"]["error"] as $key => $error) {
    if ($error === UPLOAD_ERR_OK && $_FILES["files"]["size"][$key] < $maxSize) {
        $tmpName = $_FILES["files"]["tmp_name"][$key];
        $fileType = $_FILES["files"]["type"][$key];

        // Ensure the MIME type is valid before processing
        if (!in_array($fileType, $allowedTypes)) {
            continue; 
        }

        // Attempt to create a resource from the temp file
        // Note: Do not move_uploaded_file() yet.
        $imageResource = null;
        $dimensionsValid = false;

        switch ($fileType) {
            case 'image/gif':
                $imageResource = @imagecreatefromgif($tmpName);
                break;
            case 'image/png':
                $imageResource = @imagecreatefrompng($tmpName);
                break;
            case 'image/jpeg':
            case 'image/pjpeg':
                $imageResource = @imagecreatefromjpeg($tmpName);
                break;
        }

        if ($imageResource !== false) {
            list($width, $height) = getimagesize($tmpName);
            
            // Free memory immediately as we don't need the resource anymore for validation
            if (function_exists('imagedestroy')) {
                imagedestroy($imageResource); 
            }

            if ($width <= $maxWidth && $height <= $maxHeight) {
                $dimensionsValid = true;
            } else {
                // Image is too large
                echo '<p>Image dimensions must be less than ' . $maxWidth . 'px width and ' . $maxHeight . 'px height.</p>';
                // Optional: unlink($tmpName) to clean up invalid uploads immediately
                if (file_exists($tmpName)) {
                    unlink($tmpName); 
                }
            }
        } else {
            echo '<p>Invalid image format or unable to read dimensions.</p>';
            // Clean up failed upload
            if (file_exists($tmpName)) {
                unlink($tmpName);
            }
        }
    }
}

Why Not Just Use getimagesize()?

You might wonder why the code snippet above calls getimagesize() rather than relying solely on $_FILES["files"]["size"]. The $_FILES array provides the total file size in bytes, which is useful for limiting bandwidth and storage usage. However, it offers zero information regarding resolution.

The function getimagesize() reads the binary header of the image. It returns an array containing width, height, type, and MIME type. Crucially, this function does not require you to have uploaded the file to your final destination (move_uploaded_file) to work; it simply needs a valid path to the temporary stream.

Trade-offs and Considerations

There is a performance cost to reading image dimensions. Opening a file pointer and parsing binary headers takes CPU time. If you are processing hundreds of images per request, this I/O operation can become a bottleneck. In high-throughput scenarios, some developers prefer to skip dimension checks entirely during the initial upload phase and perform lazy validation when the image is actually needed for rendering.

However, if your use case involves displaying these images in a gallery or a grid, enforcing strict dimension limits upfront prevents server-side errors later when attempting to resize extremely large images. It also saves valuable disk space by rejecting oversized files immediately rather than storing them and processing them later.

Remember that $_FILES["files"]["type"] is provided by the client and can be spoofed. Always cross-reference with getimagesize() or use finfo_file() to verify the actual MIME type before trusting the client's assertion. The example above handles this by attempting to instantiate an image resource; if the function returns false, the file is not a valid image of that specific format, regardless of what the user claimed it was.

Our network