Home > Article > Backend Development > How to Identify the True IP Address Behind Proxy Servers?
Identifying the True IP Address Behind Proxy Servers
Retrieving a visitor's IP address using standard PHP methods such as $_SERVER['REMOTE_ADDR'] may not provide accurate information if the visitor is accessing your website through a proxy server.
To address this issue, consider utilizing the following PHP code:
<code class="php">function getUserIP() { // Obtain the IP address of the visitor behind CloudFlare 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']; $ip = null; 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 IP address [Ex: 177.87.193.134]</code>
This function first checks if the visitor is using CloudFlare, a popular proxy service. If so, it retrieves the real IP address using the HTTP_CF_CONNECTING_IP header.
Next, it considers three potential IP sources: HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, and REMOTE_ADDR. It validates each IP address and selects the most reliable one.
By adopting this approach, you can effectively obtain the actual IP address of your visitors, even when they are behind proxy servers.
The above is the detailed content of How to Identify the True IP Address Behind Proxy Servers?. For more information, please follow other related articles on the PHP Chinese website!