Get visitors IP address with PHP


Home - Tutorials - Networking

This article demonstrates how to get visitors real IP address using PHP width code examples and security remarks.

Tutorial info:


Name:Get visitors IP address with PHP
Total steps:1
Category:Networking
Level:Normal

Bookmark Get visitors IP address with PHP



Bookmark and Share

Step 1 - Get visitors IP address with PHP


Get visitors IP address with PHP

Getting a visitors IP address can be important for a lot of reasons, for example, logging, geo targeting, redirecting the user and so on. All of the IP relevant informations can be found in the $_SERVER array. The simplest way to get the visitors IP address is as simple as the following code, by reading the REMOTE_ADDR field:

Code:
  1. $ip = $_SERVER['REMOTE_ADDR'];


However this solution is not completely accurate, as if the user sits behind a proxy, then you will get the IP of the proxy server and not the real user address. Fortunately we can make some additional refinement to get more accurate results. Proxy servers extend the HTTP header with new property which stores the original IP. The name of this filed is X-Forwarded-For or Client-Ip. If one of these fields are present in the HTTP header then you can read their values from the $_SERVER array as in the first example. So you need to check all the 3 possibilities:

Code:
  1. echo "Remote addr: " . $_SERVER['REMOTE_ADDR']."<br/>";
  2. echo "X Forward: " . $_SERVER['HTTP_X_FORWARDED_FOR']."<br/>";
  3. echo "Clien IP: " . $_SERVER['HTTP_CLIENT_IP']."<br/>";
  4.  

Using this information is quite easy now to create a simple function which returns the probably real ip of the site visitor:

Code:
  1. function getIp() {
  2.     $ip = $_SERVER['REMOTE_ADDR'];
  3.  
  4.     if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  5.         $ip = $_SERVER['HTTP_CLIENT_IP'];
  6.     } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  7.         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  8.     }
  9.  
  10.     return $ip;
  11. }
  12.  

Note: Why I wrote “probably real”? Because the values of the X-Forwarded-For and Client-Ip are not reliable. It is quite easy to manipulate these values. For example simply installing a Firefox plugin to change header information. Because of this don’t use this IP alone for security purposes.







Tags: get user ip, http header, real ip, find ip, php ip, get ip

Get visitors IP address with PHP - Table of contents
Step 1 - Get visitors IP address with PHP


Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0117