Home >Backend Development >PHP Tutorial >How to Reliably Retrieve a Client's IP Address in PHP?

How to Reliably Retrieve a Client's IP Address in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 14:10:161033browse

How to Reliably Retrieve a Client's IP Address in PHP?

Retrieve the Client's IP Address in PHP

PHP's $_SERVER superglobal provides a method to retrieve the IP address of website visitors. However, incorrect IP addresses may be returned using the conventional $_SERVER['REMOTE_ADDR'] approach. This discrepancy can be attributed to multiple factors, including proxy servers and load balancers.

To obtain an accurate IP address, consider alternative server variables. The following two functions are interchangeable and demonstrate how to do so:

Using getenv():

function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

Using $_SERVER:

function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

These functions prioritize the most reliable IP address option available in the server variables, ensuring an accurate representation of the client's IP address.

The above is the detailed content of How to Reliably Retrieve a Client's IP Address in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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