Before we go any further, never trust data sent from the client. The most reliable value in PHP you can hope is $_SERVER[‘REMOTE_ADDR’] that contains the real IP address of the connecting party. But the client can be hidden behind a proxy server.
The proxy server may have set the $_SERVER[‘HTTP_X_FORWARDED_FOR’] in which this variable server can be easily spoofed. Those variable are just HTTP headers which can be set by anyone who understand how HTTP works. The IP value from $_SERVER[‘HTTP_X_FORWARDED_FOR’] can be an internal IP from the LAN behind the proxy or even can be set by the client without a proxy.

This $_SERVER[‘REMOTE_ADDR’] variable is the real physical IP address value that the web server received the connection from and that the response will be sent to. Here’s some sample code:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
} else {

Don’t forget to sanitize the data before you go any further

$valid = filter_var( $ip , FILTER_VALIDATE_IP);

So if you are going to save the client IP address, make sure you save both $_SERVER[‘REMOTE_ADDR’] and $_SERVER[‘HTTP_X_FORWARDED_FOR’]. In a case that you want to save into database, make sure your field have space at least 45 characters to accommodates IPv6.