为博客评论添加IP归属地
本文发布于 606 天前,其中的信息可能已经有所发展或是发生改变。

近期国内各大平台都在添加IP归属地,我也想趁这股风潮添加一下。

本文提到的免费数据库、API均为非商业授权,请勿用于商业用途。

在主题的issues中找到了一款兼容插件[1]

但很可惜的是由于使用的是免费IP库,所以不支持IPV6,博客很早开启了IPV6支持,导致一部分评论不显示IP归属地,于是我就将其安装上后暂时搁置了。

今天访问友链网站,注意这样到一篇文章[2]

https://mcenjoy.cn/1241/
为博客评论添加IP归属地-随意之光的港湾 · 博客

据了解,其IPV6支持是通过访问ip-api.com的API获取,于是参考其代码对插件进行了修改,现在可以显示所有IP属地。

修改的部分代码

function curl_get_https($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $tmpInfo = curl_exec($curl);
    curl_close($curl);
    return $tmpInfo;
}
if (!function_exists('get_user_city_e')) :
	function get_user_city_e($ip){
$result = curl_get_https("http://ip-api.com/json/".$ip."?lang=zh-CN");
$json=json_decode($result,true);
 
if ($json == null){$c = " 获取失败 ";}

elseif($json["status"]=="success" && $json["country"]=="中国") {
    $c = $json['regionName'];
}
elseif($json["status"]=="success"){
  $c = $json['country'];

}
else{
    $c = " 未知 ";
}
  return $c;}            
endif;
if (!function_exists('easy_location_handle_comment')) :
	function easy_location_handle_comment($comment_text)
	{
		$comment_ID = get_comment_ID();
		$comment = get_comment($comment_ID);
		if ($comment->comment_author_IP && get_user_city($comment->comment_author_IP)) {
			$comment_text .= '<div class="comment--location" id="offline"><i class="fa fa-map-marker" aria-hidden="true"></i>&nbsp;IP属地(仅供参考):' . get_user_city($comment->comment_author_IP) . '</div>' ;
		}
		elseif($comment->comment_author_IP){
	    	$comment_text .= '<div class="comment--location" id="api"><i class="fa fa-map-marker" aria-hidden="true"></i>&nbsp;IP属地(仅供参考):' . get_user_city_e($comment->comment_author_IP) . '</div>' ;
		}
		else{
		$comment_text .= '<div class="comment--location">未获取评论IP地址</div>'    ;
		}
		return $comment_text;
	}
endif;

匆匆修改,可能会存在问题,欢迎进行指正。

更新记录

2023年3月20日 :添加当访问api网站失败时" 获取失败 "的提示,避免直接抛出php报错。

为博客评论添加IP归属地(https://blog.suiyil.cn/3358.html)随意之光发布于随意之光博客,其中原创内容均以知识共享署名-非商业性使用-以相同方式共享 4.0 国际许可协议(CC BY-NC-SA 4.0)进行许可,转载与引用请注明出处,详见版权协议与免责声明

评论

  1. 博主 置顶
    Windows
     山东省
    1 年前
    2023-3-20 17:43:41

    注意:目前,ip-api.com国内访问异常,国内服务器可能需要寻找其他IPv6库。

  2. Android
     山西省
    1 年前
    2023-2-03 13:23:38

    测试

  3. 评论测试
    Android
     山东省
    1 年前
    2023-1-25 10:47:26

    测试评论

    • 博主
      评论测试
      Android
       山东省
      1 年前
      2023-1-25 10:52:43

      测试一下

  4. 邮件测试
    Android
     山东省
    1 年前
    2023-1-25 10:44:35

    随意之光评论邮件测试

  5. i
    Linux
     山东省
    1 年前
    2022-11-02 12:56:50

    遵守评论规则|´・ω・)ノ

  6. Windows
     广东省
    2 年前
    2022-9-03 12:46:58

    感觉不错,我吸收了(~ ̄▽ ̄)~ 谢谢大佬分享

本文评论已关闭
上一篇
下一篇