简体   繁体   中英

php/jquery - check if image in url really exists

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

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";
}
$headers = @get_headers($imageurl);

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM