June 26, 2012 learn_php

Get IP Address using PHP

Get IP Address using PHP

Now days, getting a visitors 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 visitors IP address is by reading the REMOTE_ADDR field within this $_SERVER array. The following example ilustrates how easy it is:

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 3 of the following indecis(including the first one I gave above). The other 2 are the following:

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:

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 plugins 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.

Leave a Reply

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

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.