查看: 4|回复: 0

[技术教程] 简单使用php获取gravatar头像

[复制链接]
  • 打卡等级:常驻代表
  • 打卡总天数:40
  • 打卡月天数:4
  • 打卡总奖励:341
  • 最近打卡:2025-07-11 08:55:56
发表于 前天 17:13 | 显示全部楼层 |阅读模式
Gravatar 头像已经成为了博客、论坛等非常流行的通用头像,他能使你的网站的留言者根据自己的邮箱匹配不同的 Gravatar 头像。但不可否认的是 Gravatar 头像的服务器及缓存服务器位于国外,由于受到了干扰,国内无法打开 Gravatar 头像服务器及缓存服务器,导致了 Gravatar 头像无法显示,这样严重的拖累了网站的打开速度,甚至会因为一篇文章的留言非常多,需要加载几百个 Gravatar 头像图片,大量 HTTP 请求的发送,直接导致了网页加载缓慢、网站出现打不开的现象。

之前用的是v2ex的源,感觉速度不太理想,所以以下代码就诞生了。
  1. header("Content-type:image/png");
  2. $path_info  = $_SERVER['PATH_INFO'];
  3. $path_array = explode('/', $path_info);

  4. $m     = ($path_array[2] != null) ? $path_array[2] : $_GET['m'];
  5. $s     = isset($_GET['s']) ? $_GET['s'] : '60';
  6. $r     = isset($_GET['r']) ? $_GET['r'] : 'g';
  7. $query = http_build_query(array(
  8.     'gravatar_id' => $m,
  9.     'size'        => $s,
  10.     'rating'      => $r,
  11. ));

  12. $url = 'https://secure.gravatar.com/avatar/index.php?' . $query;
  13. $ch  = curl_init();
  14. curl_setopt($ch, CURLOPT_URL, $url);
  15. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  16. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  17. $res = curl_exec($ch);
  18. echo $res;
  19. curl_close($ch);
复制代码
如果要使用缓存的话,Github 上有一个现成的项目。
要应用在 WordPress 中,将以下代码加入 functions.php 中:
  1. function MyAvatar($avatar) {
  2.         $avatar = str_replace(array("www.gravatar.com/avatar","0.gravatar.com/avatar","1.gravatar.com/avatar","2.gravatar.com/avatar","secure.gravatar.com"),"beta.api.kotori.love/gravatar",$avatar);
  3.         return $avatar;
  4. }
  5. add_filter('get_avatar', 'MyAvatar');
复制代码
Nginx反代配置
  1. http {
  2.   proxy_cache_path  /var/cache/nginx levels=1:2 keys_zone=gravatar:8m max_size=10000m inactive=600m;
  3.   proxy_temp_path /var/cache/nginx/tmp;

  4.   server {
  5.     listen 80;
  6.     server_name ruby-china.org;

  7.     location /avatar {
  8.       proxy_redirect     off;
  9.       proxy_set_header   Host $host;
  10.       proxy_set_header   X-Forwarded-Host $host;
  11.       proxy_set_header   X-Forwarded-Server $host;
  12.       proxy_set_header   X-Real-IP        $remote_addr;
  13.       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
  14.       proxy_pass         http://gravatar.com;
  15.       proxy_cache ruby_china;
  16.       proxy_cache_valid  200 302  300d;
  17.       proxy_cache_valid  404 502  1m;
  18.       expires           7d;
  19.     }
  20.   }
  21. }
复制代码
原文地址:https://kotori.love/archives/fetch-gravatar-with-php
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表