How to Get the Real Visitor IP Address Behind Proxies?

Barbara Streisand
Release: 2024-11-06 17:54:02
Original
264 people have browsed it

How to Get the Real Visitor IP Address Behind Proxies?

Getting Real Visitor IPs Behind Proxies

In cases where visitors use proxies, the standard PHP method $_SERVER['REMOTE_ADDR'] may not provide the actual visitor IP address. To address this issue, consider utilizing the following PHP code:

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

echo $user_ip; // Output real visitor IP address</code>
Copy after login

This code checks for CloudFlare networks and adjusts the IP address accordingly. It then examines HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, and REMOTE_ADDR in that order, prioritizing IPs with valid formats. By implementing this code, you can obtain the real visitor IP address, even when they are behind a proxy.

The above is the detailed content of How to Get the Real Visitor IP Address Behind Proxies?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!