Retrieving the Real Visitor IP Address Despite Proxy Usage
The PHP code commonly used to obtain a visitor's IP address is:
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:
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();
This code assigns the IP address to the variable $user_ip, which can then be utilized as needed within your PHP script.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3