Web Info and IT Lessons Blog...

Sunday, 8 February 2015

How to get the ip address of user in PHP?

The previous lesson of PHP lessons series was Cookies in PHP and in this lesson we will learn to find the ip address of user in PHP.

Ip Address in PHP

There are certain pre-defined global variables in PHP that can be accessed from any where in your PHP script. One such variable is $_SERVER, which stores information related to headers, locations and paths. To find the ip address of user we will make use of the server variable to find the remote address of the user i.e


$ip = $_SERVER['REMOTE_ADDR'];

The above code will store the ip address of the user in the variable $ip. It's the easiest way to get the ip address of the end user in PHP. But this method is not reliable in all scenarios i.e when a user a accessing your website through a proxy server you will only get the address of the proxy server not the ip address of the end user. Fortunately there is a way to deal with this problem in PHP and that is the HTTP_X_FORWARDED_FOR header set by the proxy site. We can get the ip address of the end user by accessing the HTTP_X_FORWARDED_FOR header like this:


$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

Now we know there can be two scenarios

1. When user is not using any proxy
2. When user is using a proxy

So the real implementation of code to get the end user's ip can be something like this:


if($_SERVER['HTTP_X_FORWARDED_FOR']){
   $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} 
else{ 
   $ip = $_SERVER['REMOTE_ADDR'];
}

The above code checks if the the HTTP_X_FORWARDED_FOR header is set then use this header to get the ip address of the user else get the user ip using remote address method.

Related Posts
Include and Require Statements in PHP
Session in PHP
Cookies in PHP
Get and Post methods in PHP

No comments:

Post a Comment