How To Retrieve Gravatar Image URL in PHP?

By Faruque Ahamed Mollick

On many of the websites where there are registration and login system, we can see that a profile picture uploading system is present. Facebook, Twitter, Google may be the example. Well, often a profile picture is known as “avatar image” on some of the websites.

Gravatar is a service which delivers avatar images or profile pictures. Actually, Gravatar is owned by WordPress. Anyone can set avatar image for his/her email on Gravatar. That means from Gravatar, one can manage all the avatar image for multiple emails.

How to convert JSON string to PHP Array?

Email validation in PHP using FILTER_VALIDATE_EMAIL

Well, we can easily retrieve the avatar image from Gravatar. Here we are going to see how to get the avatar image from Gravatar in PHP language.

Before we are going through the code let’s see the URL that we have to process to retrieve the avatar image:



https://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default_image ) . "&s=" . $size

You can see that we are sending three variables to the URL. These are md5 encode of email. with trim function, default image URL with URL encoded and the size in pixel.

Country information on clicking map – PHP script

Ajaxify Weather Forecast PHP Script Source Code

Now we are going to create our own function where we just need to provide these variables as theĀ parameter. Below is our code to create the PHP function:

<?php
function retrieve_gravatar_url($email,$default_image,$size)
{
  $gravatar_url = "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default_image ) . "&s=" . $size;
  return $gravatar_url;
}
?>

And the usage of this function is given below:

<?php $avatar_url = retrieve_gravatar_url('[email protected]','defaults-mg',55); ?>
<img src="<?php echo $avatar_url; ?>" alt="Avatar" />

That’s it. We are now able to display Gravatar image for a particular email of Gravatar.

With this process, we can use Gravatar for our web application. In default WordPress installation this features has been used. WordPress CMS also retrieve image URL from Gravatar and use it as the profile picture. That’s why if someone startsĀ his/her own website using WordPress CMS application then he/she can she profile picture in the comment section if the email of the comment writer is on Gravatar and has an avatar image there.

 

Leave a Reply

Your email address will not be published. Required fields are marked *