domino
domino

Reputation: 7345

How to check if remote file is image using get_headers

$headers = get_headers("http://www.domain.com/image.jpg");

How do I make sure the file is an actual image using this?

Upvotes: 1

Views: 2600

Answers (4)

Samarth Karia
Samarth Karia

Reputation: 3

It is pretty simple with this method,

$headers = get_headers( 'http://covers.openlibrary.org/b/isbn/9780141323367-S.jpg' );
$image_exist = implode(',',$headers);
if (strpos($image_exist, 'image') !== false) 
{
    echo 'Yups';
}
else 
{
    echo "Nopes";
}

Upvotes: 0

Jeroen
Jeroen

Reputation: 13257

Like Eugen Rieck said, you can't be sure whether it's an image without downloading it. It's always possible for the server to change the Content-Type header to make it seem like an image.

However, after you've downloaded it, you can check it by using this function:

if (getimagesize('path/to/image.jpg')) {
    // image
}
else {
    // not an image
}

If you want to use the Content-Type anyways, this should work:

$headers = array_change_key_case (get_headers ('http://example.com/exampleimage.jpg', 1) );
if (substr ($headers ['content-type'], 0, 5) == 'image') {
    // image
}
else {
    // not an image
}

array_change_key_case() is used to make all array keys lowercase so the case doesnt make a difference.

Upvotes: 4

Ander2
Ander2

Reputation: 5658

Look for "Content-Type" in the result array and check that it starts with 'image/'

Upvotes: 1

Eugen Rieck
Eugen Rieck

Reputation: 65324

Not at all. The headers might or might not tell you (via Content-type), what the server thinks this is - but nothing hinders you to put e.g. myfile.zip on a webserver, then rename it to myfile.jpg. The webserver will serve it with Content-type: image/jpeg, which it definitly is not.

Upvotes: 3

Related Questions