Use this helper function to quickly and easily load up an avatar image based on a user's e-mail address. This will utilize the Gravatar service which will load a user's set avatar, or if one does not exist a dynamically generated avatar.

This function will return a secure Gravatar URL based on the MD5 hash of the e-mail address passed in. Optional parameters include the size which defaults to 80x80 pixels, the image type which defaults to identicon, and the image extension which defaults to jpg.

/**
 * Returns the Gravatar URL based on the e-mail address passed to it. For the default image the choices
 * explained are:
 *
 * 404: do not load any image if none is associated with the email hash, instead return an HTTP 404
 * mm: (mystery-man) a simple, cartoon-style silhouetted outline of a person (does not vary by email hash)
 * identicon: a geometric pattern based on an email hash
 * monsterid: a generated 'monster' with different colors, faces, etc
 * wavatar: generated faces with differing features and backgrounds
 * retro: awesome generated, 8-bit arcade-style pixelated faces
 * blank: a transparent PNG image (border added to HTML below for demonstration purposes)
 *
 * @param string $email The e-mail address of the gravatar we want to display
 * @param int $size The size in pixels for the width and height of the gravatar, can be from 1 to 2048
 * @param string $default_image Default is 'identicon'. Choices are: 404 | mm | identicon | monsterid | wavatar | retro
 * @param string $avatar_ext
 * @return string
 */
function gravatar ($email, $size = 80, $default_image = 'identicon', $avatar_ext = 'jpg'): string
{
    $url = 'https://www.gravatar.com/avatar/';
    $url .= md5(strtolower(trim($email))) . '.' . $avatar_ext . '?s=' . $size . '&d=' . $default_image;

    return $url;
}

This code snippet was published on It was last edited on

0

0 Comments

  • Votes
  • Oldest
  • Latest