Get Client IP Address
Reads a client IP address safely from server data and only trusts forwarded headers when explicitly allowed.
Purpose
Reads a client IP address safely from server data and only trusts forwarded headers when explicitly allowed.
Snippet details
ContextSecurityLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Get Client IP Address.
*
* Purpose:
* Reads the client IP from server data and avoids trusting proxy headers unless
* the caller explicitly marks the request as coming through a trusted proxy.
*
* @param array $server_data Usually `$_SERVER`.
* @param bool $trust_forwarded_header Whether to trust HTTP_X_FORWARDED_FOR.
* @return string Valid IP address or empty string.
*/
function ogSnippetGetClientIpAddress(array $server_data, bool $trust_forwarded_header = false): string {
$ip_address = '';
if (isset($server_data['REMOTE_ADDR']) === true) {
$remote_address = trim((string) $server_data['REMOTE_ADDR']);
if (filter_var($remote_address, FILTER_VALIDATE_IP) !== false) {
$ip_address = $remote_address;
}
}
if ($trust_forwarded_header === true && isset($server_data['HTTP_X_FORWARDED_FOR']) === true) {
$forwarded_parts = explode(',', (string) $server_data['HTTP_X_FORWARDED_FOR']);
foreach ($forwarded_parts as $forwarded_part) {
$candidate_ip = trim($forwarded_part);
if (filter_var($candidate_ip, FILTER_VALIDATE_IP) !== false) {
$ip_address = $candidate_ip;
break;
}
}
}
return $ip_address;
}
$sample_server = array(
'REMOTE_ADDR' => '203.0.113.42',
'HTTP_X_FORWARDED_FOR' => '198.51.100.77, 10.0.0.12'
);
$client_ip = ogSnippetGetClientIpAddress($sample_server, false);
echo 'Client IP: '.$client_ip;