技术知识库

帮助中心 >  产品文档 >  云服务器 >  WordPress禁止国外IP访问网站
/**
* WordPress 显示评论者IP归属地PHP函数
* https://www.landui.com
**/
function aliuyun_getRealIp()
{
  $ip=false;
  if(!empty($_SERVER["HTTP_CLIENT_IP"])){
    $ip = $_SERVER["HTTP_CLIENT_IP"];
  }
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
    if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
    for ($i = 0; $i < count($ips); $i++) {
      if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
        $ip = $ips[$i];
        break;
      }
    }
  }
  return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
 
function aliuyun_locate($ip) {
$ip=aliuyun_getRealIp();
    if(empty($ip)) $ip = get_comment_author_IP();
    $ch = curl_init();  
    $timeout = 5;  
    curl_setopt ($ch, CURLOPT_URL, 'http://www.landui.com/service/getIpInfo.php?ip='.$ip);  
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
    $file_contents = curl_exec($ch);  
    curl_close($ch);  
    $result = json_decode($file_contents,true);
    if ($result['data']['country'] != '中国') {
        wp_redirect( 'https://www.landui.com' );
    } else {
        echo '<!-- 运营商是'.$result['data']['isp'].',IP是'.$ip.',禁止外国IP访问!! -->';
    }
}
add_action( 'wp_footer', 'aliuyun_locate' );

你只需将以上代码加入到主题中的function.php即可。刷新页面试试效果,

如果主题中出现那么恭喜你,封禁成功了!!

其中,wp_redirect( ‘https://www.landui.com’ );

可替换为wp_die(‘IP’, ‘IP!’, array(‘response’ => ‘503’));

这样直接503,SEO也还行。如果不替换的话,国外IP访问全部跳转到

https://www.landui.com这个链接

自己修改即可。


提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: