How to get Gravatar image from Email - Helper Class

How to get Gravatar image from Email - Helper Class

How to get Gravatar image from Email - Helper Class



<?php

/**
* Gravatar Helper
*/
class GravatarHelper
{
  /**
  * validate_gravatar
  *
  * 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;
  }


  /**
  * gravatar_image
  *
  *  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 = 'http://www.gravatar.com/avatar/' . $hash. '?s='.$size.'&d='.$d;
    return $image_url;
  }


}


Realtime Use in View Part Then

<?php if(validate_gravatar($email)): ?>
   <img src="<?= 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





In this Laravel Video Tutorial, I've showed you-
1) How to get gravatar image from email 2) How to check if there is a gravatar image for any email 3) Display a gravatar image in frontend from an email

How to get Gravatar image from Email - Helper Class How to get Gravatar image from Email - Helper Class Reviewed by Maniruzzaman Akash on July 25, 2018 Rating: 5

3 comments:

Powered by Blogger.