Home > Backend Development > PHP Tutorial > PHP gets the client's IP

PHP gets the client's IP

高洛峰
Release: 2016-10-20 13:55:54
Original
904 people have browsed it

1.REMOTE_ADDR: The IP address of the user's computer browsing the current page
2.HTTP_X_FORWARDED_FOR: The gateway of the user's computer browsing the current page
3.HTTP_CLIENT_IP: The client's IP

Use $_SERVER["REMOTE_ADDR"] in PHP to obtain The IP address of the client, but if the client uses a proxy server to access, the IP address obtained is the IP address of the proxy server, not the real client IP address. To obtain the client's real IP address through a proxy server, use $_SERVER["HTTP_X_FORWARDED_FOR"] to read it.

However, something to note is that not every proxy server can use $_SERVER["HTTP_X_FORWARDED_FOR"] to read the real IP of the client. Some of the IPs read by this method are still the IP of the proxy server.

Another thing to note is that if the client does not access through a proxy server, the value obtained with $_SERVER["HTTP_X_FORWARDED_FOR"] will be empty.

/**
 * 获取客户端IP
 * @return string
 */
function get_client_ip()
{
    $realip = "";
    if ($_SERVER['HTTP_X_FORWARDED_FOR'] && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else if ($_SERVER['HTTP_CLIENT_IP']  && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP']))
    {
        $realip = $_SERVER['HTTP_CLIENT_IP'];
    }
    else if($_SERVER['REMOTE_ADDR'] && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP']))
    {
        $realip = $_SERVER['REMOTE_ADDR'];
    }

    return $realip;
}
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template