Home > Article > Backend Development > How to Get the Real Visitor IP Address When Using Proxies?
How to Retrieve the Authentic Visitor IP Address
When attempting to obtain a visitor's IP address using the default PHP code , it may not retrieve the actual IP address when a proxy is employed. This article aims to address this issue by providing a robust solution.
The provided PHP code addresses this challenge effectively:
<?PHP function getUserIP() { // Handle CloudFlare network's IP masking 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 IP address [Ex: 177.87.193.134] ?>
This code methodically checks for the visitor's IP address using various headers, accounting for potential proxy usage, including those employed by CloudFlare. It meticulously filters the retrieved IP addresses to provide the most accurate representation of the visitor's true IP address.
By implementing this code, you can ensure that you consistently obtain the authentic IP addresses of your visitors, regardless of whether they are utilizing proxies or not.
The above is the detailed content of How to Get the Real Visitor IP Address When Using Proxies?. For more information, please follow other related articles on the PHP Chinese website!