Enquire

PHP – Best Way To Get User IP Address

PHP Scripts, Tips & Tricks

A lot of people rely on the $_SERVER[‘REMOTE_ADDR’] global variable to retrieve a user IP address, but there’s a better more reliable way of retrieving a vistor’s/user’s IP Address…

Retrieve IP Address function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function getIpAddress()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
    	//check ip from share internet
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   
    {
    	//check ip is pass from proxy
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip = $_SERVER['REMOTE_ADDR'];
    }
 
    return $ip;
}
 
echo getIpAddress();

Comments

Leave a reply

Your email address will not be published. Required fields are marked *

X