Implementing gravatars with PHP is quite simple. PHP provides strtolower()
, hash()
, and urlencode()
functions, allowing us to create the gravatar URL with ease. Assume the following data:
$email = "someone@somewhere.com";
$default = "https://www.somewhere.com/homestar.jpg";
$size = 40;
You can construct your gravatar url with the following php code:
$grav_url = "https://www.gravatar.com/avatar/" . hash( "sha256", strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s=" . $size;
Once the gravatar URL is created, you can output it whenever you please:
<img src="<?php echo $grav_url; ?>" alt="" />
Example Implementation
This function will allow you to quickly and easily insert a Gravatar into a page using PHP:
/**
* Get either a Gravatar URL or complete image tag for a specified email address.
*
* @param string $email The email address
* @param int $size Size in pixels, defaults to 64px [ 1 - 2048 ]
* @param string $default_image_type Default imageset to use [ 404 | mp | identicon | monsterid | wavatar ]
* @param bool $force_default Force default image always. By default false.
* @param string $rating Maximum rating (inclusive) [ g | pg | r | x ]
* @param bool $return_image True to return a complete IMG tag False for just the URL
* @param array $html_tag_attributes Optional, additional key/value attributes to include in the IMG tag
*
* @return string containing either just a URL or a complete image tag
* @source https://gravatar.com/site/implement/images/php/
*/
function get_gravatar(
$email,
$size = 64,
$default_image_type = 'mp',
$force_default = false,
$rating = 'g',
$return_image = false,
$html_tag_attributes = []
) {
// Prepare parameters.
$params = [
's' => htmlentities( $size ),
'd' => htmlentities( $default_image_type ),
'r' => htmlentities( $rating ),
];
if ( $force_default ) {
$params['f'] = 'y';
}
// Generate url.
$base_url = 'https://www.gravatar.com/avatar';
$hash = hash( 'sha256', strtolower( trim( $email ) ) );
$query = http_build_query( $params );
$url = sprintf( '%s/%s?%s', $base_url, $hash, $query );
// Return image tag if necessary.
if ( $return_image ) {
$attributes = '';
foreach ( $html_tag_attributes as $key => $value ) {
$value = htmlentities( $value, ENT_QUOTES, 'UTF-8' );
$attributes .= sprintf( '%s="%s" ', $key, $value );
}
return sprintf( '<img src="%s" %s/>', $url, $attributes );
}
return $url;
}