This article is about retrieved user real IP address by using PHP script. It's very important for a website to track visitors IP address and location. You can monitor your website's traffic location using IP address. So, why late? Let's see how to get user real IP address using PHP. At first, we will create a function for that. This function will detect real IP from the visitor.
function getrealip()
{
if (isset($_SERVER)){
if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
if(strpos($ip,",")){
$exp_ip = explode(",",$ip);
$ip = $exp_ip[0];
}
}else if(isset($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}else{
$ip = $_SERVER["REMOTE_ADDR"];
}
}else{
if(getenv('HTTP_X_FORWARDED_FOR')){
$ip = getenv('HTTP_X_FORWARDED_FOR');
if(strpos($ip,",")){
$exp_ip=explode(",",$ip);
$ip = $exp_ip[0];
}
}else if(getenv('HTTP_CLIENT_IP')){
$ip = getenv('HTTP_CLIENT_IP');
}else {
$ip = getenv('REMOTE_ADDR');
}
}
return $ip;
}
This function is ready to detect users IP address now we need to create a full script to use this function. Let's create a file for that name as index.php.then put this code in this script,
index.php
<?php
function getrealip()
{
if (isset($_SERVER)){
if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
if(strpos($ip,",")){
$exp_ip = explode(",",$ip);
$ip = $exp_ip[0];
}
}else if(isset($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}else{
$ip = $_SERVER["REMOTE_ADDR"];
}
}else{
if(getenv('HTTP_X_FORWARDED_FOR')){
$ip = getenv('HTTP_X_FORWARDED_FOR');
if(strpos($ip,",")){
$exp_ip=explode(",",$ip);
$ip = $exp_ip[0];
}
}else if(getenv('HTTP_CLIENT_IP')){
$ip = getenv('HTTP_CLIENT_IP');
}else {
$ip = getenv('REMOTE_ADDR');
}
}
return $ip;
}
$MyipAddress = getrealip();
echo $MyipAddress;
?>
This script is ready to use. If you execute this script on the local server like wamp or xampp then this script will show your IP 127.0.0.1 that means your localhost IP address. When you will execute this script in the online server then this script will show your IP address which is provided by your ISP.Normally we get client IP address using $_SERVER['REMOTE_ADDR'] but using this script we will get user real IP if any user will use proxy & multiple IP.
$_SERVER["HTTP_X_FORWARDED_FOR"] will retrieve real IP address if any user will use proxy and $_SERVER["HTTP_CLIENT_IP"] checks if multiple IP addresses exist.
This is an advance method to retrieve any client's IP address.