How to Fetch a Gravitar Image With PHP

posted Monday, December 8th 2014 at 8:45 AM by

Gravitar Icon

When I added Gravitar support for Homebräu I ran into a little hiccup for users that didn't have a Gravitar image. I needed to find a way to check to see if a Gravitar image exists in PHP, then stop Gravitar from returning the default image, which is just the boring Gravitar icon.

I managed to work it out by adding the query string parameter d=404 to the Gravitar image URL and checking it using the get_headers() function in PHP. When the Gravitar service sees that parameter, it will return a HTTP/1.0 404 Not Found status code if the user doesn't have a gravitar. It will return a HTTP/1.1 200 OK status code if it was able to fetch the Gravitar successfully.

Here's how we can check to see if the Gravitar exists using PHP.


$email = "ak@adamkonieska.com";

// the Gravitar service requires the email to be hashed when sent, we'll use MD5 in PHP
// the s query string parameter sets the size of the gravitar, in this case its 64x64
// the d=404 query string parameter tells the Gravitar service to return a 404 status code if the user doesnt have an image
$gravitar = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( stripslashes($email) ) ) ) . "?s=64&d=404";

// use get_headers to determine the http status code for the users Gravitar
$response = get_headers($gravitar);

//check to see if the Gravitar exists
if($response[0] != "HTTP/1.0 404 Not Found") {

	$img = "<img src=\"" . $gravitar . "\" />";

} else {

	// TODO logic in case this user doesnt have a Gravitar

Further Reading

PHP get_headers() function
Creating the hashed email in PHP
Gravitar image requests

Hope that helps! Let me know how that works for you in the comments.

Share This:



View (0) Comments Post a Comment
  • Replying to Adam Konieska on How to Fetch a Gravitar Image With PHP