In this tutorial you will learn about the How to Get User IP Address in PHP and its application with practical example.
How to Get User IP Address in PHP
There may be many occasions we need to get user IP address to track user’s activity. In PHP, you can simply get the visitor’s IP address using the $_SERVER[‘REMOTE_ADDR’] variable.
- $_SERVER[‘REMOTE_ADDR’] – It Returns the IP address of the current user.
Example:-
1 |
echo "User IP - ".$_SERVER['REMOTE_ADDR']; |
But, $_SERVER[‘REMOTE_ADDR’] may not always return the true IP address of the client. If user is connected to the Internet through Proxy Server then $_SERVER[‘REMOTE_ADDR’] in PHP just returns the the IP address of the proxy server not of the client’s machine. So here, I have create a simple function in PHP to find the real IP address of the visitor’s machine.
Simple PHP function to get client IP address
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function getUserIpAddr(){ if(!empty($_SERVER['HTTP_CLIENT_IP'])){ //ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //ip pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }else{ $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } echo 'User Real IP - '.getUserIpAddr(); |