Skip to content

Início / Optitravel / Helpers / HttpHelper

getClientIp

Signature

  • public static function getClientIp(?array $server = null): ?string
  • function get_client_ip(?array $server = null): ?string - Global helper function that calls HttpHelper::getClientIp().

Description

Retrieves the real client IP address, taking into account common reverse proxy headers and Cloudflare. The function validates candidate IPs and prefers public addresses when multiple entries are present (for example in HTTP_X_FORWARDED_FOR).

Order of preference:

  1. HTTP_CF_CONNECTING_IP
  2. HTTP_X_FORWARDED_FOR (first public IP, otherwise first valid)
  3. HTTP_CLIENT_IP
  4. REMOTE_ADDR

If running on CLI or having STDIN defined, the function returns 127.0.0.1.

Parameters

  • $server (optional): An associative array with server parameters (defaults to $_SERVER). Useful for unit testing.

Usage Example

// use it with the global helper
$ip = get_client_ip();

// with a custom server array
$ip = get_client_ip(['HTTP_X_FORWARDED_FOR' => '203.0.113.5, 10.0.0.1']);

Return

  • string|null - A valid IP address string, or null if none could be determined.

↑ (Última atualização: 23/04/2026)