PHP Image Requests
Implementing gravatars with PHP is quite simple. PHP provides strtolower()
, md5()
, and urlencode()
functions, allowing us to create the gravatar URL with ease. Assume the following data:
1 2 3 |
You can construct your gravatar url with the following php code:
1 | $grav_url = "https://www.gravatar.com/avatar/" . md5( strtolower ( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s;=" . $size ; |
Once the gravatar URL is created, you can output it whenever you please:
1 | <img src= "<?php echo $grav_url; ?>" alt= "" /> |
Example Implementation
This function will allow you to quickly and easily insert a Gravatar into a page using PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Get either a Gravatar URL or complete image tag for a specified email address. * * @param string $email The email address * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ] * @param string $d Default imageset to use [ 404 | mp | identicon | monsterid | wavatar ] * @param string $r Maximum rating (inclusive) [ g | pg | r | x ] * @param boole $img True to return a complete IMG tag False for just the URL * @param array $atts Optional, additional key/value attributes to include in the IMG tag * @return String containing either just a URL or a complete image tag */ function get_gravatar( $email , $s = 80, $d = 'mp' , $r = 'g' , $img = false, $atts = array () ) { $url .= md5( strtolower ( trim( $email ) ) ); $url .= "?s=$s&d;=$d&r;=$r" ; if ( $img ) { $url = '<img src="' . $url . '"' ; foreach ( $atts as $key => $val ) $url .= ' ' . $key . '="' . $val . '"' ; $url .= ' />' ; } return $url ; } |