获取真实IP并与掩码进行比较

时间:2019-05-12 16:06:37

标签: php

出现问题。以前,该代码通过REMOTE_ADDR可以正常工作。我们决定安装DDOS Protect。从此刻起,我们将根据getUserIP()脚本的示例获得真实IP,因为它返回了代理IP。 但是,为什么我的代码返回false,尽管在代码示例中,字符串稍低一些,但100%相同。 我在做什么错了?

<?php
    function getUserIP()
    {
        if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
                  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
                  $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
        }
        $client  = @$_SERVER['HTTP_CLIENT_IP'];
        $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
        $remote  = $_SERVER['REMOTE_ADDR'];

        if(filter_var($client, FILTER_VALIDATE_IP))
        {
            $ip = $client;
        }
        elseif(filter_var($forward, FILTER_VALIDATE_IP))
        {
            $ip = $forward;
        }
        else
        {
            $ip = $remote;
        }

        return $ip;
    }

    $real_ip = getUserIP();
    echo $real_ip."<br>"; //my real IP from DDOS Protect == 109.237.13.17

    function isAllowed($ip) {
        global $link;
        $whitelist = array('111.111.111.111', '109.237.13.*', '68.71.44.*');
        if(in_array($ip, $whitelist)) {
            return true;
        }
        else {
            foreach($whitelist as $i){
                $wildcardPos = strpos($i, "*");
                if($wildcardPos !== false && substr($real_ip, 0, $wildcardPos) . "*" == $i)
                    return true;
            }
        }
        return false;
    }
    echo isAllowed($real_ip) ? 'true' : 'false'."<br>"; // HERE IS FALSE

    //FOR TEST ECHO
    $whitelist = array('111.111.111.111', '109.237.13.*', '68.71.44.*');
    if(in_array($ip, $whitelist)) {
        echo "IP IN ARRAY == TRUE";
    }
    else {
        foreach($whitelist as $i){
            $wildcardPos = strpos($i, "*");
            if($wildcardPos !== false && substr($real_ip, 0, $wildcardPos) . "*" == $i)
                echo substr($real_ip, 0, $wildcardPos) . "*"."   ==   ".$i."<br>"; // BUT HERE ALL IS TRUE
        }
    }    
?>

在出口处:

109.237.13.17 false 109.237.13.* == 109.237.13.*

1 个答案:

答案 0 :(得分:0)

固定:我添加

global $real_ip;

内部isAllowed函数