Here's a simple one liner
$ip = $_SERVER['HTTP_X_FORWARDED_FOR']?: $_SERVER['HTTP_CLIENT_IP']?: $_SERVER['REMOTE_ADDR']; ?: is similar to JS's EDIT:
Above code may return || operator when used thisreserved addresses (like 10.0.0.1), a list of addresses of all proxy servers on the way, etc. To handle these cases use the following code:
function valid_ip($ip) { // for list of reserved IP addresses, see https://en.wikipedia.org/wiki/Reserved_IP_addresses return $ip && substr($ip, 0, 4) != '127.' && substr($ip, 0, 4) != '127.' && substr($ip, 0, 3) != '10.' && substr($ip, 0, 2) != '0.' ? $ip : false; } function get_client_ip() { // using explode to get only client ip from list of forwarders. see https://en.wikipedia.org/wiki/X-Forwarded-For return @$_SERVER['HTTP_X_FORWARDED_FOR'] ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2)[0] : @$_SERVER['HTTP_CLIENT_IP'] ? explode(',', $_SERVER['HTTP_CLIENT_IP'], 2)[0] : valid_ip(@$_SERVER['REMOTE_ADDR']) ?: 'UNKNOWN'; } echo get_client_ip();