Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Wednesday, October 29, 2014

Getting Visitor's Real IP Address with PHP

Couch ModePrint It

In this post, I will show you how to grab the IP address of the visitor using PHP. The code that is used will try to get the real IP.

The basic code


However, don't rely on the above basic code. Read below.

PHP Code

Here is the PHP code wrapped in a function.

/* Function to get the client IP address from environment variables */
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
        $ipaddress = 'UNKNOWN';
    return $ipaddress;

How to get IP

Actually, its simple as that:


/* IP address is in the variable: $client_ip */
echo "Your IP is ".$client_ip;

How to log IP

Well, this is just a bonus code tip. If you ever wanted to save a list of IP logs (for some security reasons e.g in your admin panel), than you can use the following code as an example.

/* get_client_ip() function here */

/* the log file name */
$file = "ip_logs.txt"; 

/* Append the IP to the file */
file_put_contents($file, get_client_ip(), FILE_APPEND | LOCK_EX);

Another but Same PHP function

This function is same as the one written above but this one makes use of the SERVER VARIABLES.

/* Function to get the client IP address from $_SERVER (SERVER VARIABLES) */
function get_client_ip() {
    $ipaddress = '';
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
        $ipaddress = 'UNKNOWN';
    return $ipaddress;

This code relies on headers sent by the client so remember that these headers can be faked too. Infact, there's no way to get 100% correct IP address of the visitor.

You can use this code for redirecting the visitor according to his IP location or store the IP for logging and security or any other purpose (it would be great if you share how you handle IPs).