Getting client IP with PHP

Time:2020-12-25

REMOTE_ Addr is the IP address when your client “shakes hands” with your server. If anonymous proxy is used, remote_ Addr will display the IP of the proxy server (proxy can be used in nginx_ set_ header X-Forwarded-For $remote_ Addr; to solve the problem).
HTTP_ CLIENT_ IP is the HTTP header sent by the proxy server. In the case of super anonymous proxy, returns a value of none. Again, remote_ Addr will also be replaced with the IP of the proxy server.

/**
 *Get client IP
 * @return string
 * @author bashlog
 * @date 2020-09-11 14:19
 */
function get_client_ip()
{
    foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $server_key)
    {
        if (array_key_exists($server_key, $_SERVER)) {
            $ip = trim($_SERVER[$server_key]);
            //FILTER_ FLAG_ NO_ PRIV_ Range - the required value is not within the private range IP specified by the RFC (for example, 192.168.0.1).
            //FILTER_ FLAG_ NO_ RES_ Range - the required value is not in the reserved IP range. This flag accepts IPv4 and IPv6 values.
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }
    return '';
}

Recommended Today

Statistics In PostgreSQL

This article is similar to the source reading of an article, a preliminary introduction to the PostgreSQL statistical information module. The reason why we choose PostgreSQL instead of other databases is that PostgreSQL always performs well in various papers when we see some comparison of design estimation. Statistics collected in PG In PostgreSQL, the collected […]