How to get Gravatar image from Email - Helper Class and Advanced implementation
Categories - Laravel PHP Framework PHP Tags - PHP Laravel   Maniruzzaman Akash   3 years ago   1270   2 minutes   0

How to get Gravatar image from Email - Helper Class and Advanced implementation

Gravatar is one of the most beautiful systems to use images on any of the websites. Gravatar has given us the ability to use and email and get some customized email as we need. Let's learn about that today.

 

How to get Gravatar image from Email - Helper Class

First, we would make a helper class to get and set the gravatar image. Let's do it quickly.

<?php

/**
* Gravatar Helper Class
*
* Validate Gravatar Image and Set the URL
*/
class GravatarHelper
{

  /**
  * Validate the Email
  *
  * Check if the email has any gravatar image or not
  *
  * @param  string  $email Email of the User
  *
  * @return boolean true, if there is an image. false otherwise
  */
  public static function validate_gravatar($email) {
    $hash = md5($email);
    $uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404';
    $headers = @get_headers($uri);
    if (!preg_match("|200|", $headers[0])) {
      $has_valid_avatar = FALSE;
    } else {
      $has_valid_avatar = TRUE;
    }
    return $has_valid_avatar;
  }


  /**
  * Get Gravat Image URL
  *
  * Get the Gravatar Image From An Email address
  *
  * @param  string  $email User Email
  * @param  integer $size  size of image
  * @param  string  $d     type of image if not gravatar image
  *
  * @return string        gravatar image URL
  */
  public static function gravatar_image( $email, $size=0, $d="" ) {
    $hash = md5($email);
    $image_url = 'https://www.gravatar.com/avatar/' . $hash. '?s='.$size.'&d='.$d;
    return $image_url;
  }
}

 

Use in Controller Part
Now, we can get in PHP file - 
<?php

$email = 'manirujjamanakash@gmail.com';

$isEmailValidated = GravatarHelper::validate_email( $email );

if ( $isEmailValidated ) {
   echo GravatarHelper::gravatar_image($email, 100); // 
}
 
Can Use also in View Part
Now, we can use this also directly in view file if we need too.
 
<?php if(GravatarHelper::validate_gravatar($email)): ?>
   <img src="<?= GravatarHelper::gravatar_image($email, 100) ?>" alt="" />
<?php endif; ?>​
 

Code Parts

validate_gravatar($email)
Pass an email to this function. If there is an email in gravatar.com for this email this function will return true , otherwise it'll return false

gravatar_image($email, $size="", $d="")
Pass an email, size(optional), d(optional)  to this function. This will return an image URL if there is any image


Reference Article 

About how to use Gravatar Email as Imagehttps://en.gravatar.com/site/implement/images/php

Good Class-Based Examplehttps://github.com/emberlabs/gravatarlib

 

 

Previous
PHP If-else-elseif and Switch-case
Next
PHP String Functions - All necessary String functions in PHP to manage strings better.