Many times we need to collect the visitor IP address to track activity and for the security reason. It’s very easy to get the IP address of visitor in PHP. PHP $_SERVER variable provides an easy way to get user IP address.
The simplest way to get the visitor IP address is using the REMOTE_ADDR in PHP.
- $_SERVER[‘REMOTE_ADDR’] – Returns the IP address of the user from which viewing the current page
echo 'User IP - '.$_SERVER['REMOTE_ADDR'];
But sometimes REMOTE_ADDR does not returns the correct IP address of the user. The reason behind this is to use Proxy. In that situation, use the following code to get real IP address of user in PHP.
//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();