Free

Here is one single line script and the other one is the function

Single line script to get IP address using PHP

– The single-line script is enough to get the user’s IP

  <?php

    echo $ip_address = $_SERVER['REMOTE_ADDR'];

?> 
A simple function to get IP address in all the cases.

– $_SERVER is a PHP array that is set by the server

– in some time these headers can be easily spoofed by the users by setting an IP address themselves. or users can change IP using tools
– Following PHP script covers the majority of the scenario and returns the user’s IP address.

  <?php 

/**
 * Gets the User's IP address.
 */

echo "IP Address = " . get_ip_address();
function get_ip_address()
{
    $ip_address = '';
    if (! empty($_SERVER['HTTP_CLIENT_IP'])) {
        //  get shared ISP IP address...
        $ip_address = $_SERVER['HTTP_CLIENT_IP'];
    } else if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // check IPs passing through proxy servers.....
        // check if multiple IP addresses are set and take the first one from that 
        $ip_addressList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        foreach ($ip_addressList as $ip) {
            if (! empty($ip)) {
                // if you prefer, you can check for valid IP address here...
                $ip_address = $ip;
                break;
            }
        }
    } else if (! empty($_SERVER['HTTP_X_FORWARDED'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED'];
    } else if (! empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
        $ip_address = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    } else if (! empty($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_FORWARDED_FOR'];
    } else if (! empty($_SERVER['HTTP_FORWARDED'])) {
        $ip_address = $_SERVER['HTTP_FORWARDED'];
    } else if (! empty($_SERVER['REMOTE_ADDR'])) {
        $ip_address = $_SERVER['REMOTE_ADDR'];
    }
    return $ip_address;
}



 ?> 
7
0
4.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Hi, I’m K2. I help build websites and I’m available for
freelance work.

0
Would love your thoughts, please comment.x
()
x