0

I need to know how to limit PHP from downloading a file more than 5mb returning an error if it does. But if it passes I want it to check for the width and height. But I don't want it to download the file again to check for the width and height. Here is my current code:

<?php list($width, $height) = getimagesize('http://www.spacetelescope.org/static/archives/images/large/heic0601a.jpg'); echo $width.' x '.$height;

thanks.

webdev
  • 339
  • 1
  • 9
  • Your best bet is probably to use cURL, issue a HEAD request against the URL and inspect the `Content-Length` header first, before downloading and checking the dimensions. – Dominic Barnes Dec 19 '12 at 22:52

1 Answers1

2

Because a jpeg image doesn't actually store its dimensions somewhere in the file you cannot do this.

To prevent it from trying to get the dimensions of the image if its larger than 5MB you can do a head request to the server to get the size of the file. see PHP: Remote file size without downloading file for how to do this.

It would be something like:

function getRemoteFileSize($remoteFile){
    $ch = curl_init($remoteFile);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    $data = curl_exec($ch);
    curl_close($ch);
    if ($data === false)
        return 0;

    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) 
        return (int)$matches[1];

    return 0;
}

$remoteFile = 'http://www.spacetelescope.org/static/archives/images/large/heic0601a.jpg';

if(getRemoteFileSize($remoteFile) < 5 * 1024 * 1024){
    list($width, $height) = getimagesize($remoteFile); 
    echo $width.' x '.$height;
}
Community
  • 1
  • 1
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70