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.
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
//ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
//ip pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = $_SERVER['REMOTE_ADDR'];
echo 'User Real IP - '.getUserIpAddr();