Click here to Skip to main content
Click here to Skip to main content

Get IP Address using PHP

By , 8 Oct 2012
Rate this:
Please Sign up or sign in to vote.

Get IP Address using PHP

Nowadays getting a visitor's IP address is very important for many reasons. These reasons can include logging, targeting, redirecting and etc. IP information can be found in the $_SERVER array. The easiest way to get the visitor's IP address is by reading the REMOTE_ADDR field within this $_SERVER array. The following example illustrates how easy it is:

<?php $ip = $_SERVER['REMOTE_ADDR']; ?>

This solution, however, is not entirely accurate due to proxy applications that users may have, meaning that you will get the IP of the proxy server and not the real user address. Luckily, PHP gives us a few more indices to get more accurate results. Proxy servers extend the HTTP header with new property which stores the original IP. In order to be more accurate with your reading, you would need to verify all three of the following indices (including the first one I gave above). The other two are the following:

<?php 
    $remote = $_SERVER['REMOTE_ADDR'];

    $forwarded = $_SERVER['HTTP_X_FORWARDED_FOR'];

    $client_ip = $_SERVER['HTTP_CLIENT_IP'];
?>

Now that we know how to get the IP address from a user, then we can go ahead and create a reusable function that will indeed return and IP address if it is present, or return false otherwise:

<?php 
    function getIp(){

        $ip = $_SERVER['REMOTE_ADDR'];     
        if($ip){
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            return $ip;
        }
        // There might not be any data
        return false;
    }
?>

Note: Even with more Indices to play around with, it does not mean that this will still be 100% accurate. It is easy to manipulate these values using browser plug-ins to change header information, proxy applications or even proxy websites. Because of this, I recommend you to use more information from the user, such as MAC address and the use of cookies.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

jotorres
Software Developer
Puerto Rico Puerto Rico
As a computer scientist, I strive to learn more everyday in my field. Everything I learn, I share with my community by writing articles for future references.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 8 Oct 2012
Article Copyright 2012 by jotorres
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid