Dennis Hackethal
Dennis Hackethal

Reputation: 14305

Check image size in url

I found a nifty little php function to check whether a url is an image - is there also a way to determine whether that image is e.g. > 1mb?

SOLUTION FOUND:

I found a viable solution here: php how to get web image size in kb?

Upvotes: 0

Views: 6495

Answers (2)

Developer Gee
Developer Gee

Reputation: 402

I would refer to this post, I think it will answer your question. Easiest way to grab filesize of remote file in PHP?

There are 2 approaches (that I am aware of). One is to use CURL and fetch only the headers (more efficient, less reliable), and file_get_contents (more reliable, less efficient).

Using CURL you can get just the CONTENT_LENGTH header which is the file size. Then you can do simple math from there to see if it is over 1mb. The problem there is that the remote server may not support that feature.

By using strlen(file_get_contents("YOUR URL")) you can get the total byes in the file, but the script has to download the file first, which is a problem if it is a large image.

To check the file type you can use substr to check the file extension.

Something like this could work, but has its own problems

$ext = substr($URL, -3, 3);

if($ext == 'jpg' || $ext == 'gif') {
   //is image
}else{
   //not image
}

Upvotes: 1

Michael Robinson
Michael Robinson

Reputation: 29508

From: https://stackoverflow.com/a/3894706/187954

<?php
$headers = get_headers('http://humus101.com/wp-content/uploads/2009/11/Hummus-soup.jpg');
$size = null;
foreach($headers as $h){
    /** look for Content-Length, and stick it in $size **/
}
if ($size === null){ //we didn't get a Content-Length header
    /** Grab file to local disk and use filesize() to set $size **/
}

echo "image is $size bytes";

Upvotes: 2

Related Questions