How to get IP address in PHP

1 Comment »

Using getenv:

<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>

Please note that the function ‘getenv’ does not work if your Server API is ASAPI (IIS). In this case use $_SERVER["REMOTE_ADDR"].

Here is an interesting function to get the real IP address:

function getRealIpAddr()
{
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;
}

or even better

function getIpAddress() {
return (empty($_SERVER['HTTP_CLIENT_IP'])?(empty($_SERVER['HTTP_X_FORWARDED_FOR'])?
$_SERVER['REMOTE_ADDR']:$_SERVER['HTTP_X_FORWARDED_FOR']):$_SERVER['HTTP_CLIENT_IP']);
}

One very important thing is that there is no way to find the IP address of a computer that’s behind the anonymous proxy.


One Response to “How to get IP address in PHP”

  1. By Loy87 on Oct 22, 2009 | Reply

    And humans expect us to act normally? ,

Post a Comment