Search code examples
phpexceptionget-headers

Exception handling with get_meta_tags() & get_headers()?


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!


Solution

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