Getting visitor IP address with PHP

We can easily get IP Address of visitor with php environment variables .User IP Address was stored in following php Environment variables $_SERVER[‘REMOTE_ADDR’],$_SERVER[‘HTTP_CLIENT_IP’] and $_SERVER[‘HTTP_X_FORWARDED_FOR’].

most common practice for to get IP address of visitor with php is

1 <?php
2 $ip=$_SERVER['REMOTE_ADDR'];
3 echo 'User ip Address'.$ip;
4 ?>

We can’t trust above script generated ip address if user use proxy sever it simple return proxy IP.So to get user’s real IP address we should check for proxy and shared servers first.i have wrote one php function to get real IP address of visitor.

01 <?php
02 function GetUserIp() {
03 if(isset($_SERVER['HTTP_CLIENT_IP'])) // check for shared servers
04 {
05 $ip = $_SERVER['HTTP_CLIENT_IP'];
06 }
07 elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) // check for proxy servers
08 {
09 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
10 } else {
11 $ip = $_SERVER['REMOTE_ADDR']; // general method
12 }
13 list($ip) = explode(',',$ip);
14 return $ip;
15 }
16 echo GetUserIp(); // print ip address
17 ?>
Advertisements
Categories: PHP

2 thoughts on “Getting visitor IP address with PHP

  1. Pingback: PHP « amithmehta
  2. I think this function is also a good soloution to find users real IP address.

    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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s