PHP code example of horde / service_gravatar

1. Go to this page and download the library: Download horde/service_gravatar library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

horde / service_gravatar example snippets


use Horde\Service\Gravatar\Gravatar;
use Horde\Service\Gravatar\ValueObject\GravatarConfig;

// Simple facade API
$gravatar = new Gravatar($httpClient, $requestFactory);

// Get Gravatar hash
$hash = $gravatar->getId('[email protected]');
// Returns: '0c83f57c786a0b4a39efab23731c7ebc'

// Get avatar URL
$avatarUrl = $gravatar->getAvatarUrl('[email protected]', 80);
// Returns: 'http://www.gravatar.com/avatar/hash?s=80'

// Get profile data
$profile = $gravatar->getProfile('[email protected]');
// Returns: array with profile information

use Horde\Service\Gravatar\ValueObject\GravatarConfig;

$config = GravatarConfig::secure();
$gravatar = new Gravatar($httpClient, $requestFactory, $config);

$avatarUrl = $gravatar->getAvatarUrl('[email protected]', 80);
// Returns: 'https://secure.gravatar.com/avatar/hash?s=80'

// Get hash
$hash = $gravatar->getId('[email protected]');

// Get avatar URL with size
$url = $gravatar->getAvatarUrl('[email protected]', 80);

// Get avatar URL with options
$url = $gravatar->getAvatarUrl('[email protected]', [
    'size' => 100,
    'rating' => 'pg',
    'default' => 'identicon',
    'forceDefault' => false,
]);

// Fetch avatar image as stream
$stream = $gravatar->fetchAvatar('[email protected]', 80);

// Get profile as array
$profile = $gravatar->getProfile('[email protected]');

use Horde\Service\Gravatar\ValueObject\Email;
use Horde\Service\Gravatar\ValueObject\AvatarOptions;
use Horde\Service\Gravatar\ValueObject\Rating;
use Horde\Service\Gravatar\ValueObject\DefaultImage;

// Create email value object
$email = Email::fromString('[email protected]');
echo $email->getDomain();        // 'example.com'
echo $email->getLocalPart();     // 'user'
echo $email->getGravatarHash();  // MD5 hash

// Configure avatar options
$options = AvatarOptions::default()
    ->withSize(200)
    ->withRating(Rating::PG)
    ->withDefault(DefaultImage::IDENTICON)
    ->withForceDefault(false);

// Get avatar with complete metadata
$result = $gravatar->getAvatarWithMetadata($email, $options);
echo $result->getUrl();                    // Full URL
echo $result->getHash();                   // Gravatar hash
echo $result->getEmail()->getAddress();    // Original email
echo $result->getOptions()->size;          // 200

// Get profile as object
$profile = $gravatar->getProfileObject($email);
echo $profile->getDisplayName();           // Display name
echo $profile->getProfileUrl();            // Profile URL
print_r($profile->getPhotos());            // Photo array
print_r($profile->getAccounts());          // Social accounts

$email = Email::fromString('[email protected]');
$email->getAddress();        // Normalized address
$email->getDomain();         // Domain part
$email->getLocalPart();      // Local part
$email->getGravatarHash();   // MD5 hash

$options = AvatarOptions::default()
    ->withSize(150)                              // 1-2048 pixels
    ->withRating(Rating::G)                      // G, PG, R, X
    ->withDefault(DefaultImage::MYSTERY_PERSON)  // or custom URL
    ->withForceDefault(false);

$options->withDefault('https://example.com/default-avatar.png');

$profile = $gravatar->getProfileObject($email);

$profile->getDisplayName();        // Display name
$profile->getPreferredUsername();  // Username
$profile->getProfileUrl();         // Profile URL
$profile->getPhotos();             // Array of photos
$profile->getAccounts();           // Social accounts
$profile->isEmpty();               // Check if profile exists
$profile->toArray();               // Raw data

// Standard HTTP
$config = GravatarConfig::standard();

// Secure HTTPS
$config = GravatarConfig::secure();

// Custom
$config = new GravatarConfig('https://custom.gravatar.com', 30);
$config = $config->withTimeout(60);

use Horde\Service\Gravatar\Exception\InvalidEmailException;
use Horde\Service\Gravatar\Exception\InvalidOptionsException;
use Horde\Service\Gravatar\Exception\ProfileNotFoundException;
use Horde\Service\Gravatar\Exception\NetworkException;

try {
    $profile = $gravatar->getProfile('[email protected]');
} catch (ProfileNotFoundException $e) {
    // Profile doesn't exist (404)
} catch (NetworkException $e) {
    // HTTP error or network failure
} catch (InvalidEmailException $e) {
    // Invalid email format
} catch (InvalidOptionsException $e) {
    // Invalid avatar options
}

use Horde\Service\Gravatar\ValueObject\DefaultImage;

$url = $gravatar->getAvatarUrl('[email protected]', [
    'size' => 80,
    'default' => DefaultImage::IDENTICON,
]);

$stream = $gravatar->fetchAvatar('[email protected]', 120);

if ($stream) {
    // Save to file
    file_put_contents('avatar.jpg', (string) $stream);
} else {
    // Avatar not found (404)
}

try {
    $profile = $gravatar->getProfileObject($email);

    if ($profile->isEmpty()) {
        echo "Profile exists but has no data";
    } else {
        echo "Display name: " . $profile->getDisplayName();
    }
} catch (ProfileNotFoundException $e) {
    echo "Profile not found";
}

// Always show default, never fetch actual Gravatar
$options = AvatarOptions::default()
    ->withSize(100)
    ->withDefault(DefaultImage::RETRO)
    ->withForceDefault(true);

$result = $gravatar->getAvatarWithMetadata($email, $options);

// Use any PSR-18 client
$httpClient = new YourPsr18Client([
    'timeout' => 30,
    'headers' => ['User-Agent' => 'MyApp/1.0'],
]);

$requestFactory = new YourPsr17RequestFactory();

$gravatar = new Gravatar($httpClient, $requestFactory);

$emails = ['[email protected]', '[email protected]', '[email protected]'];
$options = AvatarOptions::default()->withSize(80);

$avatars = [];
foreach ($emails as $emailStr) {
    $email = Email::fromString($emailStr);
    $result = $gravatar->getAvatarWithMetadata($email, $options);
    $avatars[$emailStr] = $result->getUrl();
}

$profile = $gravatar->getProfileObject($email);

foreach ($profile->getAccounts() as $account) {
    echo "{$account['shortname']}: {$account['url']}\n";
}