How to get the real IP address using php?

in PHP Code / 6 Comments

This post explains about how to get real IP address using PHP code.

How to get the real IP address using PHP by Anil Kumar Panigrahi

How to get the real IP address using PHP by Anil Kumar Panigrahi

The code will get the real IP address

 

 

<?php
function getRealIpAddress()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
//check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
echo getRealIpAddress(); // display the real IP address
?>

it will be useful.

With more than 8 years experience in PHP and Founder of Anil Labs, a blog for PHP and related posts. contributed posts regarding CodeIgniter, CakePHP and Learn PHP online ...Contact : [email protected]

Discussion 6 Comments

  1. raksha

    Nice ! function ipCheck() {
    if (getenv(‘HTTP_CLIENT_IP’)) {
    $ip = getenv(‘HTTP_CLIENT_IP’);
    }
    elseif (getenv(‘HTTP_X_FORWARDED_FOR’)) {
    $ip = getenv(‘HTTP_X_FORWARDED_FOR’);
    }
    elseif (getenv(‘HTTP_X_FORWARDED’)) {
    $ip = getenv(‘HTTP_X_FORWARDED’);
    }
    elseif (getenv(‘HTTP_FORWARDED_FOR’)) {
    $ip = getenv(‘HTTP_FORWARDED_FOR’);
    }
    elseif (getenv(‘HTTP_FORWARDED’)) {
    $ip = getenv(‘HTTP_FORWARDED’);
    }
    else {
    $ip = $_SERVER[‘REMOTE_ADDR’];
    }
    return $ip;
    }
    echo ipCheck();

    the above code shows external ip address . Ip-details.com also used to find public ip .

  2. Sajjad

    Thats a great tutorial ,
    I hope this function is also working good for get user real IP.

    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;
    }

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>