Exception handling with get_meta_tags() & get_head

2019-05-12 00:27发布

In PHP, I am using get_meta_tags() and get_headers(), however, when there is a 404, those two functions throw a warning. Is there any way for me to catch it? Thanks!

3条回答
We Are One
2楼-- · 2019-05-12 01:18

You can silence it by calling them like this:

@get_meta_tags();

You can't "catch" it (easily), but you can check the return values.

Also, you can disable or redirect warnings, see error_reporting() and ini directoves "display_errors" & similar.

查看更多
SAY GOODBYE
3楼-- · 2019-05-12 01:20

those two functions throw a warning. Is there any way for me to catch it?

You shouldn't have to care. Naturally, a E_WARNING message upon failure while developing is fine; it's even desirable, as you can instantly see that something went wrong. I can imagine though that you don't want your customers to see those warnings, but you should not be doing that per use of function, you should be doing that globally: turn display_errors off in the php.ini in the production environment, and your customers will never see such messages.

That said, if you don't want them to appear in the error logs, you'll have to check to see if the page exists before trying to retrieve the meta tags. get_headers doesn't appear to throw a warning, instead it returns an array of which the first element contains the string "HTTP/1.1 404 Not Found". You can use this to your advantage:

<?php
$url = 'http://stackoverflow.com';
$headers = get_headers( $yoururl );
preg_match( '~HTTP/1.(?:1|0) (\d{3})~', $headers[0], $matches );
$code = $matches[1];

if( $code === '200' ) {
    $tags = get_meta_tags( $url );
}

If you start using this code, mind that 200 isn't the only notification of a successful request; 304 Not Modified - for example - is equally valid.

查看更多
别忘想泡老子
4楼-- · 2019-05-12 01:24

get_headers does not throw a Warning/Error on 404, but get_meta_tags does.

So you can check the header response and do something, when it's not OK:

$url = 'http://www.example.com/';

$headers = array();
$metatags = array();

$validhost = filter_var(gethostbyname(parse_url($url,PHP_URL_HOST)), FILTER_VALIDATE_IP);
if($validhost){
    // get headers only when Domain is valid
    $headers = get_headers($url, 1);

    if(substr($headers[0], 9, 3) == '200'){
        // read Metatags only when Statuscode OK
        $metatags = get_meta_tags($url);
    }
}
查看更多
登录 后发表回答