PHP: How to get real client IP address


Read more: How to get real client IP address when you use Cloudflare

function get_client_ip() {

	// Default to REMOTE_ADDR
	$ip = $_SERVER['REMOTE_ADDR'];

	$proxy_headers = array(
		'HTTP_CF_CONNECTING_IP', // CloudFlare
		'HTTP_INCAP_CLIENT_IP', // Incapsula
		'HTTP_X_SUCURI_CLIENTIP', // Sucuri
		'HTTP_X_FORWARDED_FOR', // Any Proxy
	);

	// Check for alternate headers indicating a forwarded IP address
	foreach ( $proxy_headers as $proxy_header ) {
		if ( isset( $_SERVER[ $proxy_header ] ) ) {
			$forwarded_ips = explode( ',', $_SERVER[ $proxy_header ] );
			$forwarded_ip = array_shift( $forwarded_ips );
			if ( $forwarded_ip ) {
				$ip = $forwarded_ip;
				break;
			}
		}
	}

	return $ip;
}

Leave a Reply