Can you please tell me whether this is a good way to get the user's IP (IPv4 or IPv6)? Does someone have a better way to do this? Please take a look at the entire code, the server_params
order and the comments.
/* We are looking for ip in server params */
$server_params = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');
foreach($server_params as $server_param)
{
/* If server param exists and his value is a real ip */
if(isset($_SERVER[$server_param]) && filter_var($_SERVER[$server_param], FILTER_VALIDATE_IP))
{
/* If we are here, then means that the ip is whether IPV4 or IPV6 */
/* This means that we can set user_ip as binary - We will insert this ip into an mysql column - VARBINARY (16) */
define('user_ip',inet_pton($_SERVER[$server_param]));
break;
}
}
/* If the user_ip is not defined or the inet_pton failed (can inet_pton fail if is defined ?) */
if(!defined('user_ip') || user_ip === false) { echo 'Error. Your ip is not valid'; exit(); }