Skip to content

RESOURCES / BLOG

How to get the image size in PHP?

Whether you are validating uploads, generating responsive thumbnails, or optimizing delivery, you often need to know the width, height, and file size of images in PHP. Below is a practical, community-style Q and A covering local files, remote URLs, and some pitfalls.

How to get the image size in PHP?

I need to read both dimensions and file size for images uploaded by users and also for images fetched from remote URLs. What is the most reliable way to do this in PHP, and how should I handle different formats and performance concerns? Bonus points for examples that work with file uploads, local files, and external links.

You can retrieve image dimensions and bytes in PHP using built-in functions, the Imagick extension for performance on large files, and HTTP requests for remote sources. Here are practical patterns you can plug into your app.

<?php
$path = __DIR__ . '/images/photo.jpg';

$info = @getimagesize($path);
if ($info === false) {
    throw new RuntimeException('Not a valid image or unreadable file.');
}

$width  = $info[0];
$height = $info[1];
$mime   = $info['mime'] ?? null;

echo "Dimensions: {$width}x{$height}, MIME: {$mime}\n";
?>

getimagesize works for common formats like JPEG, PNG, GIF, and sometimes WebP.

To validate file types more robustly, check MIME with finfo:

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $path);
finfo_close($finfo);
?>Code language: HTML, XML (xml)
<?php
$bytes = filesize($path);
if ($bytes === false) {
    throw new RuntimeException('Could not read file size.');
}
echo "File size: {$bytes} bytes\n";
?>Code language: HTML, XML (xml)
<?php
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    throw new RuntimeException('No file or upload error.');
}
$tmp = $_FILES['image']['tmp_name'];

$info = @getimagesize($tmp);
if ($info === false) {
    throw new RuntimeException('Uploaded file is not an image.');
}

$width  = $info[0];
$height = $info[1];
$bytes  = filesize($tmp);

if ($width > 4000 || $height > 4000 || $bytes > 5 * 1024 * 1024) {
    throw new RuntimeException('Image exceeds limits.');
}

echo "OK: {$width}x{$height}, {$bytes} bytes\n";
?>Code language: HTML, XML (xml)

Tip: If you work with EXIF-heavy formats like JPEG, you may need to account for orientation flags. See this primer on how to check image metadata.

If allow_url_fopen is enabled, getimagesize can read URLs directly:

<?php
$url = 'https://example.com/photo.jpg';
$context = stream_context_create(['http' => ['timeout' => 5]]);
$info = @getimagesize($url, $context);
if ($info) {
    echo "Remote image: {$info[0]}x{$info[1]}\n";
}
?>

Without allow_url_fopen, fetch a small chunk and parse it:

<?php
$ch = curl_init('https://example.com/photo.jpg');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 5,
    CURLOPT_RANGE => '0-65535' // partial download is often enough
]);
$partial = curl_exec($ch);
curl_close($ch);

$info = @getimagesizefromstring($partial);
if ($info) {
    echo "Dimensions: {$info[0]}x{$info[1]}\n";
}
?>Code language: HTML, XML (xml)
<?php
$ch = curl_init('https://example.com/photo.jpg');
curl_setopt_array($ch, [
    CURLOPT_NOBODY => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 5
]);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);

if ($size >= 0) {
    echo "Remote file size: {$size} bytes\n";
} else {
    echo "Content-Length not provided. Consider a full GET as fallback.\n";
}
?>Code language: HTML, XML (xml)

For very large images or formats like TIFF or HEIC, Imagick can extract dimensions without decoding the full raster.

<?php
$img = new Imagick();
$img->pingImage($path); // fast metadata read
echo $img->getImageWidth() . 'x' . $img->getImageHeight();
?>Code language: HTML, XML (xml)

If you plan to transform or convert after reading sizes, choose efficient formats. For web delivery, see JPEG vs WebP. You can also quickly convert assets like PNG to WebP using a tool such as PNG to WebP.

If your images live in the cloud, you can get dimensions and bytes from the upload response or through an API. For example, using the Cloudinary PHP SDK, the upload call returns width, height, bytes, and format. It also lets you deliver the right size on the fly and automate format selection.

<?php
use Cloudinary\Configuration\Configuration;
use Cloudinary\Api\Upload\UploadApi;

Configuration::instance([
  'cloud' => ['cloud_name' => 'demo', 'api_key' => 'key', 'api_secret' => 'secret'],
  'url'   => ['secure' => true]
]);

$result = (new UploadApi())->upload(__DIR__ . '/images/photo.jpg', ['folder' => 'samples']);
$width  = $result['width'];
$height = $result['height'];
$bytes  = $result['bytes'];
$format = $result['format'];

echo "Uploaded: {$width}x{$height}, {$bytes} bytes, format: {$format}\n";
?>Code language: HTML, XML (xml)

After that, you can deliver resized or format-optimized variants by adding simple parameters to the delivery URL. 

  • Local files: use getimagesize for dimensions and filesize for bytes. Validate MIME with finfo.
  • Remote files: getimagesize on URLs or fetch a small chunk and use getimagesizefromstring. Use HEAD to read Content-Length.
  • Large images or exotic formats: Imagick pingImage is efficient.
  • For cloud-managed workflows, upload once and read width, height, and bytes from the API. Consider modern formats based on guidance like JPEG vs WebP.

Ready to streamline image handling from upload to delivery? Create a free Cloudinary account and start automating transformations and metadata at scale.

Start Using Cloudinary

Sign up for our free plan and start creating stunning visual experiences in minutes.

Sign Up for Free