Exception handling with get_meta_tags () & get_headers ()?

In PHP, I use get_meta_tags()and get_headers(), however, when there is 404, these two functions raise a warning. Do I have a way to catch? Thank!

+3
source share
3 answers

get_headersdoes not give a warning / error on 404, but get_meta_tagsdoes.

So, you can check the response of the header and do something when this is not normal:

$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);
    }
}
+6
source

these two functions cause a warning. Do I have a way to catch him?

. , E_WARNING ; , , - . , , , , : display_errors php.ini .

, , , , , . get_headers, , , , "HTTP/1.1 404 Not Found". :

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

, , 200 - ; 304 - , .

+2

, :

@get_meta_tags();

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

In addition, you can disable or redirect warnings, see error_reporting () and ini directoves "display_errors", etc.

-2
source

All Articles