PHP 图像请求

使用 PHP 实现 Cravatar 非常简单。 PHP 提供了 strtolower()md5()、 和 urlencode()函数,让我们可以轻松创建头像 URL 。假设以下数据:

$email = "someone@somewhere.com";
$default = "https://www.somewhere.com/homestar.jpg";
$size = 40;

您可以使用以下 php 代码构建您的头像 url:

$crav_url = "https://cravatar.cn/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s=" . $size;

创建头像 URL 后,您可以随时输出:

<img src="<?php echo $crav_url; ?>" alt="" />

实施示例

此功能将允许您使用 PHP 快速轻松地将 Cravatar 插入页面中:

/**
 * Get either a Cravatar 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
 * @source https://cravatar.com/developer/php-image-requests
 */
function get_cravatar( $email, $s = 80, $d = 'mp', $r = 'g', $img = false, $atts = array() ) {
    $url = 'https://cravatar.cn/avatar/';
    $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;
}

文档最后修改于

文派文库团队编撰