Proxy forwarding headers contain client information only when set by a trusted proxy.
What It Does
Proxy forwarding headers contain client information only when set by a trusted proxy. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Understand the primary operation and its inputs.
<?php
$trusted = ['10.0.0.10'];
$peer = '10.0.0.10';
$forwarded = '198.51.100.11';
$ip = in_array($peer, $trusted, true) ? $forwarded : $peer;
echo $ip;
Example 2: Another Case
Check failure behavior or a different execution path.
<?php
$peer = '203.0.113.7';
$header = '127.0.0.1';
$ip = $peer; // Ignore X-Forwarded-For from an untrusted peer
echo $ip;
Practical Example: Putting It to Use
Apply the behavior in a small, controlled scenario.
<?php
$forwarded = '198.51.100.2, 10.0.0.10';
$hops = array_map('trim', explode(',', $forwarded));
$first = filter_var($hops[0], FILTER_VALIDATE_IP);
echo $first ?: 'invalid'; // A full solution walks a configured trusted proxy chain
Important Behavior and Edge Cases
Do not trust X-Forwarded-For sent directly from untrusted clients; validate configured trusted proxy hops.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Handling Reverse Proxy IP Headers Safely | Proxy forwarding headers contain client information only when set by a trusted proxy. |
| Related approach | Configure an explicit trusted-proxy list in the web server and application. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Handling Reverse Proxy IP Headers Safely | Do not trust X-Forwarded-For sent directly from untrusted clients; validate configured trusted proxy hops. |
| Assuming a related mechanism has the same behavior | Configure an explicit trusted-proxy list in the web server and application. |
Key Takeaways
- Proxy forwarding headers contain client information only when set by a trusted proxy.
- Do not trust X-Forwarded-For sent directly from untrusted clients; validate configured trusted proxy hops.
- Configure an explicit trusted-proxy list in the web server and application.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.