0

I found this nifty way to check if a page really exists:

$headers=@get_headers($imageurl);
if(strpos($headers[0],'200')===false){
    echo "not valid";
    exit;
}

What I need to achieve, though, is to check whether on that page is really only an image. For example, when you try the following link: www.google.com/image.jpg it will return 200 because Google has it's own error page - however, it should be possible to find out not only that there is no image on that page, but also that an image is not the only thing on that page, even when there is other content (like here: http://www.kapstadt-entdecken.de/wp-content/gallery/robben-island/1robben-island.jpg).

How I can I achieve that?

Thanks a lot!

Dennis

0

3 Answers 3

1

You will probably want to use HEAD requests when getting headers (it doesn't do that by default):

stream_context_set_default(array(
    'http' => array(
        'method' => 'HEAD'
    )
));

Second, you can pass a second parameter to get_headers to parse it for you:

$headers = get_headers($imageurl, 1);

Then, you can check the rest as per normal:

if (strpos($headers[0], '200') === false) {
    echo "not valid";
    exit;
}

if (isset($headers['Content-Type']) && 0 === strncmp($headers['Content-Type'], 'image/', 6)) {
    echo "valid image";
} else {
    echo "probably not an image";
}
Sign up to request clarification or add additional context in comments.

5 Comments

I only need to check if it doesn't work, so I changed it to: if (!isset($headers['Content-Type']) && 0 === strncmp($headers['Content-Type'], 'image/', 6)) { echo "not valid"; exit; } doesn't work unfortunately...
The inverse is !isset($headers['Content-Type']) || 0 !== strncmp($headers['Content-Type'], 'image/', 6)
no I was mistaken. it works like a charm. although the inverse only works like this apparently: if(!isset($headers['Content-Type']) && 0 === strncmp($headers['Content-Type'], 'image/', 6))
but I agree that it should actually be || 0 !=
You should var_dump($headers); to find out why this happens, because your inverted logic is wrong, that shouldn't work.
0

also with get_headers ... one of them will be

image/png
image/jpeg
image/gif

so

$isImage = false;
foreach($headers as $header){
    if(strpos($header,'image/')==true){
        $isImage = true;
    }
}

Comments

0
$headers = @get_headers($imageurl);

$is_image = false;
foreach ($headers as $header) {
    if (strpos($header, 'Content-Type: image/') === 0) {
        $is_image = true;
        break;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.