weixin_39621456 2020-11-21 20:14
浏览 0

Input::real_ip() with proxy filtering

I use this code to get a real ip, an idea for Fuel?


function real_ip()
{
    static $ip; if (isset($ip)) return $ip;

    $ips = array();

    // get all ip's (user to server)

    foreach (array(
        'HTTP_CLIENT_IP', 
        'HTTP_X_FORWARDED_FOR', 
        'HTTP_X_FORWARDED', 
        'HTTP_X_CLUSTER_CLIENT_IP', 
        'HTTP_FORWARDED_FOR', 
        'HTTP_FORWARDED', 
        'REMOTE_ADDR') as $key) // REMOTE_ADDR as last
    {
        if (array_key_exists($key, $_SERVER))
        {
            $ips = array_merge($ips, explode(',', $_SERVER[$key]));
        }
    }

    // trim and filter the found ip's

    $ips = array_filter(array_map('trim', $ips));

    // remove valid proxies

    // http://meta.wikimedia.org/wiki/XFF_project
    // http://www.wikimedia.org/trusted-xff.html
    // xff.php is a config file with trusted proxies 

    if (count($ips) > 1 and 
        file_exists(__DIR__.'/xff.php'))
    {
        $xff = require_once __DIR__.'/xff.php';

        is_array($xff) or $xff = array();

        $ips = array_diff($ips, $xff);

        unset($xff);
    }

    // validate found ip's and return if found valid ip

    foreach (array_reverse($ips) as $ip)
    {
        if (filter_var($ip, 
            FILTER_VALIDATE_IP, 
            FILTER_FLAG_IPV4 | 
            FILTER_FLAG_NO_PRIV_RANGE |
            FILTER_FLAG_NO_RES_RANGE) !== false) return $ip;
    }

    return $ip = array_pop($ips) ?: $_SERVER['REMOTE_ADDR'];
}

该提问来源于开源项目:fuel/core

  • 写回答

0条回答 默认 最新

    报告相同问题?