最近,我进入 Typecho 后台发现,评论的IP显示的都是Cloudflare CDN的IP,那如何才能获取到用户真实的IP地址呢?
其实非常简单,Cloudflare会通过Request Headers给服务器传递真实IP。

我们先新建一个php,在里面输入以下内容:

<?php
print_r($_SERVER);
?>

再通过浏览器访问,结果如下:

Array
(
    [USER] => www
    [HOME] => /home/www
    [HTTP_CDN_LOOP] => cloudflare
    [HTTP_CF_CONNECTING_IP] => 180.**.***.**
    [HTTP_COOKIE] => __cfduid=***
    [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.9
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
    [HTTP_USER_AGENT] => ***
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_CF_VISITOR] => {"scheme":"http"}
    [HTTP_X_FORWARDED_PROTO] => http
    [HTTP_CF_RAY] => 5656aff39c0ceb95-LAX
    [HTTP_X_FORWARDED_FOR] => 180.**.***.**
    [HTTP_CF_IPCOUNTRY] => CN
    [HTTP_ACCEPT_ENCODING] => gzip
    [HTTP_CONNECTION] => Keep-Alive
    [HTTP_HOST] => lightdefend.top
    [PATH_INFO] => 
    [REDIRECT_STATUS] => 200
    [SERVER_NAME] => lightdefend.top
    [SERVER_PORT] => 80
    [SERVER_ADDR] => 172.**.**.***
    [REMOTE_PORT] => 31628
    [REMOTE_ADDR] => 172.**.**.***
    [SERVER_SOFTWARE] => ****
    [GATEWAY_INTERFACE] => CGI/1.1
    [REQUEST_SCHEME] => http
    [SERVER_PROTOCOL] => HTTP/1.1
    [DOCUMENT_ROOT] => /www/wwwroot/***
    [DOCUMENT_URI] => /****.php
    [REQUEST_URI] => /****.php
    [SCRIPT_NAME] => /****.php
    [CONTENT_LENGTH] => 
    [CONTENT_TYPE] => 
    [REQUEST_METHOD] => GET
    [QUERY_STRING] => 
    [SCRIPT_FILENAME] => /www/wwwroot/***
    [FCGI_ROLE] => RESPONDER
    [PHP_SELF] => /****.php
    [REQUEST_TIME_FLOAT] => 158176****.*****
    [REQUEST_TIME] => 158176****
)

其中HTTP_CF_CONNECTING_IP就是我们要获取的访客真实IP了。
通过php获取,代码如下:

<?php
$realip=$_SERVER['HTTP_CF_CONNECTING_IP'];
echo $realip
?>

那如何在后台评论中显示真实IP呢?
很简单,在config.inc.php中加入以下代码即可实现:

define('__TYPECHO_IP_SOURCE__', 'HTTP_CF_CONNECTING_IP');

代码加入完成,可以自己试试效果哦~

标签: none

已有 2 条评论

  1. 犬吠九天
    2020-02-19 13:19
    February 19th, 2020 at 01:19 pm
    浏览器:Chrome 78
    操作系统:Android 9

    围观

  2. 2020-04-27 13:38
    April 27th, 2020 at 01:38 pm
    浏览器:火狐浏览器 75
    操作系统:Windows 7 64位

    awa...

添加新评论