Home  >  Article  >  Backend Development  >  How to Get the Real Visitor IP Address When Proxies Are in Use?

How to Get the Real Visitor IP Address When Proxies Are in Use?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 13:39:01789browse

How to Get the Real Visitor IP Address When Proxies Are in Use?

Retrieving the Real Visitor IP Address Despite Proxy Usage

The PHP code commonly used to obtain a visitor's IP address is:

<code class="php"><?php echo $_SERVER['REMOTE_ADDR']; ?></code>

However, this method fails to capture the true IP when proxies are in play. Seeking a solution to this issue, let's delve into an alternative approach.

Custom PHP Function for IP Determination

The provided PHP code offers a comprehensive solution, considering CloudFlare connections and various other factors:

<code class="php">function getUserIP()
{
    // Handle CloudFlare connections
    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;
}
$user_ip = getUserIP();</code>

This code assigns the IP address to the variable $user_ip, which can then be utilized as needed within your PHP script.

The above is the detailed content of How to Get the Real Visitor IP Address When Proxies Are in Use?. 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