A clean, zero-dependency PHP class for working with the Gravatar API. Supports avatar image URLs, public profile data, QR codes, and the authenticated Gravatar API v3 — all through a fluent, chainable interface.
- PHP 8.1 or higher
allow_url_fopenenabled (for profile fetching and avatar existence checks)
Copy Gravatar.php into your project and include it:
require_once 'Gravatar.php';// Simple avatar URL
$gravatar = new Gravatar('user@example.com');
echo $gravatar->url();
// https://secure.gravatar.com/avatar/b58996c504c5638798eb6b511e6f49af?s=80&d=mp&r=g
// Fluent static factory
echo Gravatar::for('user@example.com')->size(200)->url();
// Drop an avatar directly into a template
echo Gravatar::for('user@example.com')
->size(120)
->rating(Gravatar::RATING_G)
->defaultImage(Gravatar::DEFAULT_IDENTICON)
->imageTag('Jane Smith', ['class' => 'avatar rounded']);Returns the full avatar image URL. Accepts optional per-call overrides so you can reuse one configured instance across multiple contexts.
$g = new Gravatar('user@example.com');
$g->size(80)->rating(Gravatar::RATING_G)->defaultImage(Gravatar::DEFAULT_MP);
echo $g->url();
// Override size for a single call without changing the instance
echo $g->url(['size' => 200]);Returns a complete, escaped <img> tag. The src, width, and height attributes are set automatically; pass $attrs to merge in anything else.
echo Gravatar::for('user@example.com')
->size(64)
->imageTag('Profile photo', [
'class' => 'avatar rounded-circle',
'loading' => 'lazy',
]);
// <img src="https://secure.gravatar.com/avatar/..." alt="Profile photo" width="64" height="64" class="avatar rounded-circle" loading="lazy">Makes a HEAD request using the 404 default. Returns true only if Gravatar has a real avatar on file for the email.
if (Gravatar::for('user@example.com')->exists()) {
echo 'Custom avatar found.';
} else {
echo 'No Gravatar registered.';
}All setters return $this for chaining.
Avatar dimensions in pixels. Gravatar returns square images. Valid range: 1–2048. Default: 80.
$g->size(256);What to show when no Gravatar exists for the email. Pass one of the built-in constants or a fully-qualified URL to your own fallback image.
$g->defaultImage(Gravatar::DEFAULT_RETRO);
$g->defaultImage('https://example.com/fallback-avatar.png');| Constant | Description |
|---|---|
DEFAULT_404 |
Return an HTTP 404 — useful for detecting missing avatars |
DEFAULT_MP |
Mystery person silhouette (default) |
DEFAULT_IDENTICON |
Geometric pattern unique to the email hash |
DEFAULT_MONSTERID |
Randomly generated monster illustration |
DEFAULT_WAVATAR |
Randomly generated cartoon face |
DEFAULT_RETRO |
8-bit pixel art |
DEFAULT_ROBOHASH |
Randomly generated robot |
DEFAULT_BLANK |
Transparent 1×1 PNG |
Maximum content rating to display. Avatars rated above this threshold fall back to the default image. Default: g.
$g->rating(Gravatar::RATING_PG);| Constant | Meaning |
|---|---|
RATING_G |
Suitable for all audiences (default) |
RATING_PG |
May contain mildly offensive content |
RATING_R |
May contain harsh content |
RATING_X |
May contain explicit content |
Always show the default image, even when a real Gravatar exists. Useful for testing fallback layouts.
$g->forceDefault();Use the HTTPS endpoint (secure.gravatar.com). Enabled by default; set to false to use www.gravatar.com over HTTP.
$g->secure(false);HTTP request timeout for profile fetches and existence checks. Default: 10.
$g->timeout(5);Gravatar generates a QR code linking to a user's profile page.
echo Gravatar::for('user@example.com')->qrCodeUrl(200);
// https://secure.gravatar.com/avatar/b58996c...?s=200echo Gravatar::for('user@example.com')->qrCodeTag(150, ['class' => 'qr-code']);Gravatar profiles are publicly accessible without an API key. Profile data is fetched once and cached on the instance for subsequent calls.
Returns the raw profile array, or null if no public profile exists or the request fails. Pass false to bypass the in-memory cache and re-fetch.
$profile = Gravatar::for('user@example.com')->fetchProfile();
if ($profile !== null) {
print_r($profile);
}Fetch any single top-level field from the profile by name.
$g = new Gravatar('user@example.com');
echo $g->profileField('displayName');
echo $g->profileField('currentLocation', 'Unknown');$g = new Gravatar('user@example.com');
echo $g->displayName(); // "Jane Smith"
echo $g->aboutMe(); // Bio / description text
echo $g->profilePageUrl(); // "https://gravatar.com/janesmith"
// Linked URLs added to the profile
foreach ($g->profileUrls() as $link) {
echo $link['title'] . ': ' . $link['value'] . PHP_EOL;
}
// Verified social accounts
foreach ($g->accounts() as $account) {
echo $account['shortname'] . ': ' . $account['url'] . PHP_EOL;
}Returns the URL for a profile in the requested format without fetching it. Useful for constructing links or feeding to your own HTTP client.
echo $g->profileUrl(Gravatar::FORMAT_JSON);
echo $g->profileUrl(Gravatar::FORMAT_VCF); // vCard download URL| Constant | Format |
|---|---|
FORMAT_JSON |
JSON (default) |
FORMAT_XML |
XML |
FORMAT_PHP |
PHP serialized |
FORMAT_VCF |
vCard |
The Gravatar API v3 exposes additional profile fields — interests, payment info, verified accounts, and more — that are not available publicly. An API key is required. Get yours at gravatar.com/developers.
Pass the key as the second constructor argument:
$g = new Gravatar('user@example.com', 'your-api-key-here');Fetches the full v3 profile as an array. Throws \RuntimeException if no API key is set.
$profile = $g->fetchAuthenticatedProfile();Returns the interests/hobbies array from the authenticated profile.
$interests = $g->fetchInterests();
foreach ($interests ?? [] as $interest) {
echo $interest['name'] . PHP_EOL;
}Returns payment and cryptocurrency wallet information.
$payments = $g->fetchPayments();Gravatar identifies users by a hash of their email address. The class uses SHA-256 (current standard). An MD5 helper is included for compatibility with older systems.
$g = new Gravatar('user@example.com');
echo $g->getHash(); // SHA-256 (used internally)
echo $g->computeHash('other@example.com'); // SHA-256 of any email
echo $g->computeMd5Hash('old@example.com'); // MD5 — legacy onlyEmail addresses are normalised (trimmed, lowercased) before hashing, matching Gravatar's own behaviour.
Change the email on an existing instance. The hash and profile cache are updated automatically.
$g = new Gravatar('first@example.com');
$g->setEmail('second@example.com');echo $g->getEmail(); // "user@example.com"
echo $g->getHash(); // "b58996c504c5638798eb6b511e6f49af..."Returns all current configuration and the computed URL as an associative array.
print_r(Gravatar::for('user@example.com')->size(100)->toArray());
// [
// 'email' => 'user@example.com',
// 'hash' => 'b58996c504...',
// 'size' => 100,
// 'default' => 'mp',
// 'rating' => 'g',
// 'forceDefault' => false,
// 'secure' => true,
// 'url' => 'https://secure.gravatar.com/avatar/...',
// ]Casting the object to a string returns the avatar URL directly.
$g = new Gravatar('user@example.com');
echo "Avatar: $g";
// Avatar: https://secure.gravatar.com/avatar/b58996c...?s=80&d=mp&r=g| Situation | Exception |
|---|---|
Invalid email address passed to constructor or setEmail() |
\InvalidArgumentException |
size() called with a value outside 1–2048 |
\InvalidArgumentException |
defaultImage() called with an unrecognised value |
\InvalidArgumentException |
rating() called with an unrecognised value |
\InvalidArgumentException |
profileUrl() called with an invalid format |
\InvalidArgumentException |
| Any authenticated API method called without an API key | \RuntimeException |
Network failures (connection timeout, DNS errors, non-2xx responses) return null from fetch methods rather than throwing, so you can handle them with a simple null check.
$profile = $g->fetchProfile();
if ($profile === null) {
// No profile, private profile, or network error
}$g = new Gravatar('user@example.com');
echo '<div class="profile-card">';
echo $g->size(96)->imageTag($g->displayName() ?? 'User', ['class' => 'avatar']);
echo '<h2>' . htmlspecialchars($g->displayName() ?? 'Unknown') . '</h2>';
echo '<p>' . htmlspecialchars($g->aboutMe() ?? '') . '</p>';
echo '</div>';$g = (new Gravatar('user@example.com'))->size(64);
$avatarUrl = $g->exists()
? $g->url()
: '/img/default-avatar.png';
echo '<img src="' . $avatarUrl . '" alt="Avatar">';$g = new Gravatar('user@example.com');
$thumbnail = $g->url(['size' => 32]);
$profile = $g->url(['size' => 128]);
$hero = $g->url(['size' => 512]);$g = new Gravatar('user@example.com');
foreach ($g->accounts() as $account) {
printf(
'<a href="%s">%s</a>' . PHP_EOL,
htmlspecialchars($account['url']),
htmlspecialchars($account['display'])
);
}| Method | Returns | Description |
|---|---|---|
__construct(email, apiKey?) |
— | Create instance; validates email |
for(email, apiKey?) |
static |
Static factory for fluent use |
setEmail(email) |
static |
Change email, invalidates cache |
getEmail() |
string |
Normalised email address |
getHash() |
string |
SHA-256 hash of the email |
computeHash(email) |
string |
SHA-256 hash of any email |
computeMd5Hash(email) |
string |
MD5 hash (legacy) |
size(int) |
static |
Set image size (1–2048px) |
defaultImage(string) |
static |
Set fallback image |
rating(string) |
static |
Set max content rating |
forceDefault(bool) |
static |
Always show fallback |
secure(bool) |
static |
Use HTTPS endpoint |
timeout(int) |
static |
Set HTTP timeout in seconds |
url(overrides?) |
string |
Build avatar URL |
imageTag(alt?, attrs?) |
string |
Build <img> HTML tag |
exists() |
bool |
Check if real avatar exists |
qrCodeUrl(size?) |
string |
QR code image URL |
qrCodeTag(size?, attrs?) |
string |
QR code <img> tag |
profileUrl(format?) |
string |
Public profile data URL |
fetchProfile(cache?) |
array|null |
Fetch public profile |
profileField(field, default?) |
mixed |
Get one profile field |
displayName() |
string|null |
Display name from profile |
aboutMe() |
string|null |
Bio from profile |
profilePageUrl() |
string|null |
Gravatar profile page URL |
profileUrls() |
array |
Linked URLs from profile |
accounts() |
array |
Verified social accounts |
fetchAuthenticatedProfile() |
array|null |
Full v3 profile (API key required) |
fetchInterests() |
array|null |
Interests from v3 profile |
fetchPayments() |
array|null |
Payment info from v3 profile |
toArray() |
array |
All config + URL as array |
__toString() |
string |
Avatar URL on string cast |
MIT