Home > Article > Backend Development > 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>
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!