Search by

rafalmasiarek / real-ip-resolver

rafalmasiarek

Secure and extensible real IP resolver for PHP applications behind proxies and load balancers.

Package info

github.com/rafalmasiarek/php-realIpResolver

pkg:composer/rafalmasiarek/real-ip-resolver

Statistics

Installs: 153

Dependents: 3

Suggesters: 2

Stars: 0

Open Issues: 2

v2.4.0 2026-09-15 23:27 UTC

README

A lightweight PHP library to resolve the real client IP address behind proxies and load balancers, hardened against header spoofing.

License

License: MIT

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.

Source: https://opensource.org/licenses/MIT

See LICENSE for full details.

Authors

Installation

composer require rafalmasiarek/real-ip-resolver

Requirements

PHP 8.1 or later.

Basic usage

Without any proxy, REMOTE_ADDR is returned directly:

use rafalmasiarek\RealIpResolver;

$resolver = new RealIpResolver();
echo $resolver->getIp();

With trusted proxies

Pass a TrustedProxy instance populated with IP addresses or CIDR ranges, then enable the headers your proxy actually sets:

use rafalmasiarek\RealIpResolver;
use rafalmasiarek\RealIpResolver\TrustedProxy;
use rafalmasiarek\RealIpResolver\IPLists\Cloudflare;

// Cloudflare setup: REMOTE_ADDR will always be a Cloudflare edge node
$resolver = new RealIpResolver(new TrustedProxy(Cloudflare::get()));
$resolver->enableCloudflareHeader(); // trust CF-Connecting-IP

echo $resolver->getIp();
use rafalmasiarek\RealIpResolver;
use rafalmasiarek\RealIpResolver\TrustedProxy;
use rafalmasiarek\RealIpResolver\IPLists\Nginx;

// Nginx setup with proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
Nginx::import(['10.0.0.1']);
$resolver = new RealIpResolver(new TrustedProxy(Nginx::get()));
$resolver->enableXForwardedForHeader();

echo $resolver->getIp();
use rafalmasiarek\RealIpResolver;
use rafalmasiarek\RealIpResolver\TrustedProxy;
use rafalmasiarek\RealIpResolver\IPLists\Nginx;

// Nginx setup with proxy_set_header X-Real-IP $remote_addr
Nginx::import(['10.0.0.1']);
$resolver = new RealIpResolver(new TrustedProxy(Nginx::get()));
$resolver->enableXRealIpHeader();

echo $resolver->getIp();

TrustedProxy accepts exact IPs and CIDR notation for both IPv4 (173.245.48.0/20) and IPv6 (2400:cb00::/32).

Header priority

When REMOTE_ADDR is trusted, headers are evaluated in this order (first match wins):

  1. CF-Connecting-IP — opt-in via enableCloudflareHeader()
  2. Forwarded: for= — opt-in via enableRFC7239(), right-to-left chain traversal
  3. X-Real-IP — opt-in via enableXRealIpHeader()
  4. X-Forwarded-For — opt-in via enableXForwardedForHeader(), right-to-left chain traversal

When is each opt-in safe?

enableCloudflareHeader() — safe when every request reaching PHP passes through Cloudflare. Cloudflare sets CF-Connecting-IP to the original client IP and cannot be spoofed by the client.

enableRFC7239() — safe when the trusted proxy explicitly sets the Forwarded header and your infrastructure strips any client-supplied Forwarded headers before they reach PHP.

enableXRealIpHeader() — safe when Nginx is configured with proxy_set_header X-Real-IP $remote_addr and strips any client-supplied X-Real-IP header.

enableXForwardedForHeader() — safe when the trusted proxy appends the connecting client's IP to the right end of the chain (proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; in Nginx). Right-to-left traversal skips trusted proxy entries and stops at the first non-trusted IP — client-injected values appear to the left of the real client IP and are never returned.

In all cases: enable only headers that your proxy is known to set or sanitize. When in doubt, leave the header disabled.

Built-in IP list providers

Cloudflare

use rafalmasiarek\RealIpResolver\IPLists\Cloudflare;

// Returns CIDR ranges from the local cache file (src/RealIpResolver/data/cloudflare.txt)
$ips = Cloudflare::get();

// Download fresh ranges from Cloudflare's official endpoints and update the local file
Cloudflare::updateList();

A GitHub Actions workflow (update-cloudflare.yml) is included to refresh the list automatically on the 1st of each month.

If the package install directory does not persist across deploys (e.g. composer install rebuilding vendor/ on every release), pass an application-managed, persistent path directly to get() and updateList():

use rafalmasiarek\RealIpResolver\IPLists\Cloudflare;

$path = '/var/www/storage/realip/cloudflare.txt';

$ips = Cloudflare::get($path);
Cloudflare::updateList($path); // no-op if the downloaded list is unchanged

To change the default path once for every call site instead of passing it each time, use setFile():

Cloudflare::setFile('/var/www/storage/realip/cloudflare.txt');

$ips = Cloudflare::get();

Localhost

use rafalmasiarek\RealIpResolver\IPLists\Localhost;

// Returns ['127.0.0.1', '::1']
$ips = Localhost::get();

Nginx

For a local Nginx reverse proxy with deployment-specific IPs:

use rafalmasiarek\RealIpResolver\IPLists\Nginx;

Nginx::import(['10.0.0.1', '10.0.0.2']);
$ips = Nginx::get();

Custom IP list

Implement IpListInterface to define your own provider:

use rafalmasiarek\RealIpResolver\IPLists\IpListInterface;

class MyProxy implements IpListInterface
{
    public static function get(): array
    {
        return ['203.0.113.0/24', '2001:db8::/32'];
    }
}

PSR-15 middleware

Install the optional dependency:

composer require psr/http-server-middleware

Then register the middleware:

use rafalmasiarek\RealIpResolver;
use rafalmasiarek\RealIpResolver\TrustedProxy;
use rafalmasiarek\RealIpResolver\IPLists\Cloudflare;
use rafalmasiarek\RealIpResolver\Middleware\RealIpResolverMiddleware;

$resolver = new RealIpResolver(new TrustedProxy(Cloudflare::get()));
$resolver->enableCloudflareHeader();
$app->add(new RealIpResolverMiddleware($resolver));

// In a route handler:
$realIp = $request->getAttribute('real_ip');

All options

// Enable X-Forwarded-For header (right-to-left chain traversal)
$resolver->enableXForwardedForHeader();

// Enable CF-Connecting-IP (Cloudflare)
$resolver->enableCloudflareHeader();

// Enable RFC 7239 Forwarded header parsing
$resolver->enableRFC7239();

// Enable X-Real-IP header (Nginx)
$resolver->enableXRealIpHeader();

// Allow private and reserved IP ranges (e.g. for internal networks or tests)
$resolver->disablePrivateReservedFilter();

Security model

The fundamental rule: a forwarding header is trusted only when you know that the proxy delivering the request both sets and sanitizes that header.

  • When no trusted proxy is configured, or when REMOTE_ADDR is not in the trusted list, all forwarding headers are ignored — REMOTE_ADDR is returned directly.
  • All forwarding headers — including X-Forwarded-For — are disabled by default and require an explicit opt-in call.

Default behaviour per header:

Header Default Enable via
X-Forwarded-For off enableXForwardedForHeader()
CF-Connecting-IP off enableCloudflareHeader()
Forwarded off enableRFC7239()
X-Real-IP off enableXRealIpHeader()

Namespace change in 1.2.0

The namespace was flattened in 1.2.0. Old imports:

use rafalmasiarek\Http\RealIpResolver\RealIpResolver;

New imports:

use rafalmasiarek\RealIpResolver;
use rafalmasiarek\RealIpResolver\TrustedProxy;
use rafalmasiarek\RealIpResolver\IPLists\Cloudflare;

Index

Classes

Interfaces

Cloudflare

class — rafalmasiarek\RealIpResolver\IPLists\Cloudflare · source

Provides Cloudflare edge server IP ranges for use as trusted proxy sources. Ranges are read from a local cache file and can be refreshed from Cloudflare's official IP list endpoints. An import() method allows overriding the list in-memory, which is useful in tests. setFile() allows relocating the cache file, which is useful for applications where the package install directory does not persist across deploys.

implements IpListInterface

Property Type Visibility Description
$cache string[]|null private static In-memory cache of loaded IP ranges.
$file string private static Absolute path to the local IP list cache file. Override via setFile().
Method Visibility Returns Summary
get() public static string[] Return the list of Cloudflare CIDR ranges from the local cache file. When $path is given, it is read instead of the configured file and the in-memory cache is bypassed entirely — the cache only ever holds the default file's content, so a per-call path would otherwise return another call's cached result.
updateList() public static bool Download fresh Cloudflare IP ranges from official endpoints and overwrite the local cache file. The file is left untouched when the downloaded list is identical to what is already on disk, so its mtime only changes on an actual update. When $path is given, it is written instead of the configured file; the in-memory cache — which only ever reflects the default file — is reset only when writing to that default.
import() public static void Override the IP list in-memory, bypassing the local cache file. Intended for use in tests to avoid filesystem access.
setFile() public static void Relocate the local cache file used by get() and updateList(). Useful when the package install directory does not persist across deploys (e.g. a composer install that rebuilds vendor/ on every release), so the cache should live under an application-managed, persistent storage path instead.
get()

Cloudflare get()

source

public static function get(?string $path): array

Return the list of Cloudflare CIDR ranges from the local cache file. When $path is given, it is read instead of the configured file and the in-memory cache is bypassed entirely — the cache only ever holds the default file's content, so a per-call path would otherwise return another call's cached result.

Param Type Description
$path string|null Cache file to read instead of the configured default.

Returns: string[]

updateList()

Cloudflare updateList()

source

public static function updateList(?string $path): bool

Download fresh Cloudflare IP ranges from official endpoints and overwrite the local cache file. The file is left untouched when the downloaded list is identical to what is already on disk, so its mtime only changes on an actual update. When $path is given, it is written instead of the configured file; the in-memory cache — which only ever reflects the default file — is reset only when writing to that default.

Param Type Description
$path string|null Cache file to write instead of the configured default.

Returns: bool — True when the file was written (new or changed), false when the downloaded list was identical to what was already on disk.

Throws When
\RuntimeException When both the IPv4 and IPv6 endpoints are unreachable.
import()

Cloudflare import()

source

public static function import(array $ips): void

Override the IP list in-memory, bypassing the local cache file. Intended for use in tests to avoid filesystem access.

Param Type Description
$ips string[] List of IP addresses or CIDR ranges.
setFile()

Cloudflare setFile()

source

public static function setFile(string $path): void

Relocate the local cache file used by get() and updateList(). Useful when the package install directory does not persist across deploys (e.g. a composer install that rebuilds vendor/ on every release), so the cache should live under an application-managed, persistent storage path instead.

Param Type Description
$path string Absolute path to the cache file.

IpListInterface

interface — rafalmasiarek\RealIpResolver\IPLists\IpListInterface · source

Contract for IP address list providers used as trusted proxy sources. Implementations may return plain IP addresses or CIDR notation ranges.

Method Visibility Returns Summary
get() public static string[] Return the list of IP addresses or CIDR ranges.
get()

IpListInterface get()

source

public static function get(): array

Return the list of IP addresses or CIDR ranges.

Returns: string[] — Array of IP addresses or CIDR blocks (e.g. '173.245.48.0/20').

Localhost

class — rafalmasiarek\RealIpResolver\IPLists\Localhost · source

Provides loopback addresses as trusted proxy sources. Useful when the application runs behind a local reverse proxy (e.g. Nginx on the same host).

implements IpListInterface

Method Visibility Returns Summary
get() public static string[] Return standard loopback addresses for IPv4 and IPv6.
get()

Localhost get()

source

public static function get(): array

Return standard loopback addresses for IPv4 and IPv6.

Returns: string[]

Nginx

class — rafalmasiarek\RealIpResolver\IPLists\Nginx · source

Provides a configurable list of trusted Nginx reverse proxy IP addresses. Unlike Cloudflare, Nginx proxy IPs are deployment-specific and must be supplied via import() before use.

implements IpListInterface

Property Type Visibility Description
$cache string[]|null private static In-memory list of trusted Nginx proxy IPs or CIDR ranges.
Method Visibility Returns Summary
get() public static string[] Return the configured list of Nginx proxy IPs or CIDR ranges.
import() public static void Set the list of trusted Nginx proxy IPs or CIDR ranges.
get()

Nginx get()

source

public static function get(): array

Return the configured list of Nginx proxy IPs or CIDR ranges.

Returns: string[]

import()

Nginx import()

source

public static function import(array $ips): void

Set the list of trusted Nginx proxy IPs or CIDR ranges.

Param Type Description
$ips string[] List of IP addresses or CIDR ranges.

RealIpResolverMiddleware

class — rafalmasiarek\RealIpResolver\Middleware\RealIpResolverMiddleware · source

PSR-15 middleware that resolves the real client IP and injects it into the request attributes as 'real_ip'. Requires psr/http-server-middleware (listed as a suggested dependency).

implements MiddlewareInterface

Depends on: RealIpResolver

Property Type Visibility Description
$resolver RealIpResolver private The resolver used to determine the real client IP.
Method Visibility Returns Summary
__construct() public — —
process() public ResponseInterface Resolve the real client IP and inject it into request attributes.
__construct()

RealIpResolverMiddleware __construct()

source

public function __construct(RealIpResolver $resolver)
Param Type Description
$resolver RealIpResolver Configured resolver instance.
process()

RealIpResolverMiddleware process()

source

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

Resolve the real client IP and inject it into request attributes.

Param Type Description
$request ServerRequestInterface Current HTTP request.
$handler RequestHandlerInterface Next middleware handler.

Returns: ResponseInterface

TrustedProxy

class — rafalmasiarek\RealIpResolver\TrustedProxy · source

Validates whether an IP address belongs to a trusted proxy range. Accepts exact IP addresses and CIDR notation for both IPv4 and IPv6 (e.g. 173.245.48.0/20, 2400:cb00::/32).

implements TrustedProxyInterface

Property Type Visibility Description
$trustedIps string[] private Trusted IP addresses or CIDR ranges.
Method Visibility Returns Summary
__construct() public — —
isTrusted() public bool Check whether the given IP address is trusted. Supports both exact string matches and CIDR range matching.
ipInCidr() private bool Check whether an IP address falls within a CIDR block. Uses inet_pton() for binary byte-level comparison, which handles both IPv4 (4-byte) and IPv6 (16-byte) addresses uniformly.
__construct()

TrustedProxy __construct()

source

public function __construct(array $trustedIps)
Param Type Description
$trustedIps string[] Trusted IP addresses or CIDR ranges.
isTrusted()

TrustedProxy isTrusted()

source

public function isTrusted(string $ip): bool

Check whether the given IP address is trusted. Supports both exact string matches and CIDR range matching.

Param Type Description
$ip string IP address to check.

Returns: bool — True if the IP matches any trusted entry.

ipInCidr()

TrustedProxy ipInCidr()

source

private function ipInCidr(string $ip, string $cidr): bool

Check whether an IP address falls within a CIDR block. Uses inet_pton() for binary byte-level comparison, which handles both IPv4 (4-byte) and IPv6 (16-byte) addresses uniformly.

Param Type Description
$ip string IP address to test.
$cidr string CIDR block, e.g. 173.245.48.0/20 or 2400:cb00::/32.

Returns: bool — True if the IP is within the block.

TrustedProxyInterface

interface — rafalmasiarek\RealIpResolver\TrustedProxyInterface · source

Contract for trusted proxy validators.

Method Visibility Returns Summary
isTrusted() public bool Determine whether the given IP address belongs to a trusted proxy.
isTrusted()

TrustedProxyInterface isTrusted()

source

public function isTrusted(string $ip): bool

Determine whether the given IP address belongs to a trusted proxy.

Param Type Description
$ip string IP address to check.

Returns: bool

RealIpResolver

class — rafalmasiarek\RealIpResolver · source

Resolves the real client IP address, protected against header spoofing. When no trusted proxy is configured, or when REMOTE_ADDR is not a trusted proxy, all forwarding headers are ignored and REMOTE_ADDR is returned directly. When REMOTE_ADDR belongs to a trusted proxy, additional headers can be trusted via explicit opt-in. All forwarding headers are disabled by default and must be enabled individually: enableCloudflareHeader() → CF-Connecting-IP enableRFC7239() → Forwarded: for= (RFC 7239), right-to-left chain enableXRealIpHeader() → X-Real-IP enableXForwardedForHeader() → X-Forwarded-For, right-to-left chain Headers are evaluated in priority order: 1. CF-Connecting-IP (opt-in) 2. Forwarded: for= (opt-in, right-to-left) 3. X-Real-IP (opt-in) 4. X-Forwarded-For (opt-in, right-to-left) Enabling a header is safe only when the trusted proxy is known to set or sanitize that header — the library cannot enforce this at the network level.

Depends on: TrustedProxyInterface

Property Type Visibility Description
$trustedProxy TrustedProxyInterface|null private Trusted proxy handler, or null when none is configured.
$filterPrivateReserved bool private Whether to reject private and reserved IP ranges.
$trustCloudflareHeader bool private Whether to trust the CF-Connecting-IP header set by Cloudflare.
$trustForwardedHeader bool private Whether to trust the RFC 7239 Forwarded header.
$trustXRealIpHeader bool private Whether to trust the X-Real-IP header set by Nginx.
$trustXForwardedForHeader bool private Whether to trust the X-Forwarded-For header.
Method Visibility Returns Summary
__construct() public — —
disablePrivateReservedFilter() public void Disable filtering of private and reserved IP ranges.
enableCloudflareHeader() public void Enable trusting the CF-Connecting-IP header set by Cloudflare. Safe only when the trusted proxy list consists exclusively of Cloudflare edge IPs, or when the infrastructure sanitizes this header for all non-Cloudflare requests.
enableRFC7239() public void Enable parsing of the RFC 7239 Forwarded header. Safe only when the trusted proxy is known to set or sanitize this header.
enableXRealIpHeader() public void Enable trusting the X-Real-IP header. Safe only when the trusted proxy is known to set or sanitize this header.
enableXForwardedForHeader() public void Enable trusting the X-Forwarded-For header. Safe only when the trusted proxy appends the client IP to the existing chain and the infrastructure strips any client-supplied X-Forwarded-For values before they reach PHP.
getIp() public string Return the real client IP address. Returns REMOTE_ADDR immediately when the direct peer is not a trusted proxy, preventing any header-based spoofing attack.
parseRFC7239() private string|null Parse an RFC 7239 Forwarded header and return the real client IP. Collects all for= node values in chain order, then traverses them right-to-left, skipping trusted proxy IPs — consistent with the X-Forwarded-For security model.
normalizeRFC7239Node() private string|null Normalize an RFC 7239 node identifier to a plain IP address string. Handles the following node forms per RFC 7239 §6: 192.0.2.60 plain IPv4 192.0.2.60:47011 IPv4 with port [2001:db8::1] IPv6 literal [2001:db8::1]:4711 IPv6 literal with port unknown / _token returns null (not an IP) Ports are validated to be in range 1–65535 with no leading zeros.
isValidPort() private bool Validate a port string per RFC 7239 / HTTP syntax. Rejects values outside 1–65535 and strings with leading zeros.
isValidIp() private bool Validate an IP address, optionally rejecting private and reserved ranges.
__construct()

RealIpResolver __construct()

source

public function __construct(?TrustedProxyInterface $trustedProxy)
Param Type Description
$trustedProxy TrustedProxyInterface|null Optional trusted proxy handler.
disablePrivateReservedFilter()

RealIpResolver disablePrivateReservedFilter()

source

public function disablePrivateReservedFilter(): void

Disable filtering of private and reserved IP ranges.

enableCloudflareHeader()

RealIpResolver enableCloudflareHeader()

source

public function enableCloudflareHeader(): void

Enable trusting the CF-Connecting-IP header set by Cloudflare. Safe only when the trusted proxy list consists exclusively of Cloudflare edge IPs, or when the infrastructure sanitizes this header for all non-Cloudflare requests.

enableRFC7239()

RealIpResolver enableRFC7239()

source

public function enableRFC7239(): void

Enable parsing of the RFC 7239 Forwarded header. Safe only when the trusted proxy is known to set or sanitize this header.

enableXRealIpHeader()

RealIpResolver enableXRealIpHeader()

source

public function enableXRealIpHeader(): void

Enable trusting the X-Real-IP header. Safe only when the trusted proxy is known to set or sanitize this header.

enableXForwardedForHeader()

RealIpResolver enableXForwardedForHeader()

source

public function enableXForwardedForHeader(): void

Enable trusting the X-Forwarded-For header. Safe only when the trusted proxy appends the client IP to the existing chain and the infrastructure strips any client-supplied X-Forwarded-For values before they reach PHP.

getIp()

RealIpResolver getIp()

source

public function getIp(): string

Return the real client IP address. Returns REMOTE_ADDR immediately when the direct peer is not a trusted proxy, preventing any header-based spoofing attack.

Returns: string — Resolved client IP address.

parseRFC7239()

RealIpResolver parseRFC7239()

source

private function parseRFC7239(string $header): ?string

Parse an RFC 7239 Forwarded header and return the real client IP. Collects all for= node values in chain order, then traverses them right-to-left, skipping trusted proxy IPs — consistent with the X-Forwarded-For security model.

Param Type Description
$header string Raw Forwarded header value.

Returns: string\|null — Extracted IP, or null when none is valid.

normalizeRFC7239Node()

RealIpResolver normalizeRFC7239Node()

source

private function normalizeRFC7239Node(string $value): ?string

Normalize an RFC 7239 node identifier to a plain IP address string. Handles the following node forms per RFC 7239 §6: 192.0.2.60 plain IPv4 192.0.2.60:47011 IPv4 with port [2001:db8::1] IPv6 literal [2001:db8::1]:4711 IPv6 literal with port unknown / _token returns null (not an IP) Ports are validated to be in range 1–65535 with no leading zeros.

Param Type Description
$value string Raw node value extracted from a for= directive.

Returns: string\|null — Plain IP address, or null when the node is not a valid IP.

isValidPort()

RealIpResolver isValidPort()

source

private function isValidPort(string $port): bool

Validate a port string per RFC 7239 / HTTP syntax. Rejects values outside 1–65535 and strings with leading zeros.

Param Type Description
$port string Raw port string from a node identifier.

Returns: bool — True when the port is a valid HTTP port number.

isValidIp()

RealIpResolver isValidIp()

source

private function isValidIp(string $ip): bool

Validate an IP address, optionally rejecting private and reserved ranges.

Param Type Description
$ip string IP address to validate.

Returns: bool — True when the IP is valid and (if filtering is on) publicly routable.