Obtain a verified client address in PHP
Prefer web-server real-IP handling
Configure NGINX real-IP handling or Apache real-IP handling first. Trust only the current Backend Communication IP Addresses shown for your service in the Dashboard. Once the web server has verified and applied the header, read its client address normally:
$clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
Application fallback with an explicit trust boundary
Use this fallback only when REMOTE_ADDR still contains the immediate connection peer, before any real-IP rewriting. If another proxy sits between X4B and PHP, configure and verify the complete trust chain at the web server instead.
The fallback keeps the original peer in $peerIp, checks that peer against the trusted addresses, and accepts only a single valid IPv4 or IPv6 address. It leaves REMOTE_ADDR unchanged. Match the address family reported by your web server; an IPv4-mapped IPv6 peer must be explicitly present in the trust list if that is how your server reports it.
$trustedProxyIps = ['192.0.2.10', '2001:db8::10'];
$trustedProxyBytes = array_map('inet_pton', $trustedProxyIps);
$peerIp = $_SERVER['REMOTE_ADDR'] ?? '';
$clientIp = $peerIp;
if (is_string($peerIp)
&& filter_var($peerIp, FILTER_VALIDATE_IP) !== false
&& in_array(inet_pton($peerIp), $trustedProxyBytes, true)) {
$forwardedIp = $_SERVER['HTTP_X_REAL_IP'] ?? null;
if (is_string($forwardedIp)
&& filter_var($forwardedIp, FILTER_VALIDATE_IP) !== false) {
$clientIp = $forwardedIp;
}
}
Use $clientIp in the application where a verified client address is needed, and retain $peerIp for connection-source auditing. Missing, malformed or comma-separated header values keep the original peer. If you changed Backend Real IP Header in HTTP Options, adjust the header lookup to match.
Verify the boundary
In an isolated test, confirm that a valid header from a trusted proxy is accepted, while a forged header from an untrusted peer and an invalid header from a trusted peer both retain the original peer. Check IPv4 and IPv6, and review the trust list after backend communication addresses change.
See Real IP for applicability and PHP's IP validation filters for address validation.
