Search code examples
phphttp-headersget-headers

get_headers() on Gravatar returning 200 instead of 404


I'm passing a URL that should generate a 404 Error, using PHP's get_headers(). In fact, if I use the URL as a link, I get a 404 Error in my browser. And if I use the URL (which is to an image file) as an img src the "Network" tab of my browser shows a 404 Error status. But when I print_r the results of @get_headers( $uri ) I see that my response returns HTTP/1.0 200 OK! What's up with that?

Is this something on the web server itself? If so, what (if anything) should I communicate to the server support to get them to address the issue?

Update

The URL I am testing against is a gravatar URL: http://0.gravatar.com/avatar/4d445fd58bf07d406345bac336c3b836?s=96&d=404&r=G


Solution

  • The URL that was being sent to get_headers() had html-escaped entities, specifically &amp; rather than an actual & ampersand token. This makes a difference to get_headers(), though its original use (<img src='{$url}'... />) didn't mind the html entities encoded version. The solution was simply to use & when building the URL.

    Specific Application for Checking the Validity of a Gravatar

    Since I encountered this in the context of checking the validity of a Gravatar, and the code that I was using was on some more-or-less "official" documentation, I'm posting this in case anyone else runs into the same issue and wants a cut-and-paste solution.

    $url = "$host/avatar/";
    $url .= $email_hash;
    $url .= '?s='.$size;
    $url .= '&d=404';
    
    $gravatar_response_code = wp_cache_get( $email_hash );
    if ( false === $gravatar_response_code ){
        $response = wp_remote_head ( $url );
        if ( is_wp_error( $response ) ){
            $gravatar_response_code = "error";
        } else {
            $gravatar_response_code = $response['response']['code'];
        }
    
        wp_cache_set( $email_hash, $gravatar_response_code, '', 300 );
    }
    
    if ( '200' == $gravatar_response_code )
        $avatar = "<img alt='{$safe_alt}' src='{$url}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
    

    Do note that certain functions wp_cache_get(), wp_remote_head() and wp_cache_set() are WordPress-specific functions. The wp_remote_head() method of the HTTP API will call curl, get_headers() or even fopen() depending on what's available so it's 100% relevant and exhibits the same behaviours as what's documented here.