PHP: How to get the Actual IP address of client

At my last post, I have talked about the remote IP address of the user. But that was the gateway address, or public IP. It wasn't the IP address of client(local network address). Some gateway from ISP are allow to transfer the client's local IP address to server.

If that is available, you can get the IP address from your PHP code using the HTTP_X_FORWARDED_FOR field from $_SERVER variable. For example the below code. It will display the client's actual IP address, if it is available.

if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ){
print $_SERVER['HTTP_X_FORWARDED_FOR'];
}


Sample output : 192.168.1.5

The above code will only print the IP address, if the x-forwarded-for header is updated by the gateway of client. Otherwise it is not possible to detect the thing. If 100 users are browsing your page, it can happen that 10 of them you can get the actual IP address, and others are only showing the gateway IP address.

Comments