ScreenshotNeo

BlogHow-to

How to Get an IP Address Using PHP

Learn how to read and validate client IPs in PHP, handle proxies safely, avoid spoofed headers, and troubleshoot IPv4 and IPv6 edge cases.

By the ScreenshotNeo team30 September 20268 min read

How to Get an IP Address Using PHP

For a normal PHP web request, read $_SERVER['REMOTE_ADDR']. It contains the address of the direct peer that connected to your web server:

<?php
$ip = $_SERVER['REMOTE_ADDR'] ?? null;

That is the client address when the browser connects directly to your server. If a reverse proxy, load balancer, CDN, or ingress controller terminates the connection first, REMOTE_ADDR may be the proxy instead. In that deployment, use a forwarded header only after you have verified that the direct peer is one of your trusted proxies and you follow that proxy’s documented format.

Always validate an address before storing it, displaying it, or using it in a policy:

<?php
$raw = $_SERVER['REMOTE_ADDR'] ?? '';
$ip = filter_var($raw, FILTER_VALIDATE_IP) ?: null;

PHP’s REMOTE_ADDR documentation describes it as “The IP address from which the user is viewing the current page.” The value is supplied by the web server, and normal HTTP variables are usually absent or meaningless when the script runs from the command line. See the PHP $_SERVER manual and the filter_var manual.

Read the direct peer address

The smallest useful PHP example handles a missing value and escapes output:

<?php
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
echo htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');

REMOTE_ADDR can contain either an IPv4 address such as 198.51.100.24 or an IPv6 address such as 2001:db8::24. Do not split an IPv6 value on colons. Treat it as one opaque string after validation.

Validate IPv4 and IPv6

<?php
$raw = $_SERVER['REMOTE_ADDR'] ?? '';
$ip = filter_var($raw, FILTER_VALIDATE_IP);

if ($ip === false) {
    http_response_code(400);
    exit('Invalid IP address');
}

echo htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');

FILTER_VALIDATE_IP accepts valid IPv4 and IPv6 syntax. It returns the filtered string on success and false on failure. If your application has a narrower requirement, add FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6. You can also use FILTER_FLAG_NO_PRIV_RANGE and FILTER_FLAG_NO_RES_RANGE when your policy must reject private or reserved ranges. Those flags are policy choices: an internal admin tool may legitimately receive private addresses.

Use a forwarded client IP behind a proxy

A reverse proxy changes the network path:

A trusted proxy can add the original client address, while PHP still sees the proxy as the direct peer.
A trusted proxy can add the original client address, while PHP still sees the proxy as the direct peer.
  1. The browser connects to the proxy.
  2. The proxy connects to PHP.
  3. PHP sees the proxy as REMOTE_ADDR.
  4. The proxy may add a header containing the original address and earlier proxy hops.

X-Forwarded-For is a de-facto header for that chain. A client can send or alter it unless your infrastructure controls and sanitizes the header. The MDN guidance for X-Forwarded-For therefore says security decisions such as rate limiting and access control must use only addresses added by a trusted proxy.

Never do this:

<?php
// Unsafe: the requester can supply this header directly.
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];

Instead, establish a trusted proxy boundary in your web server or application configuration. Only if REMOTE_ADDR belongs to a configured proxy range should you parse its forwarded header.

A conservative, application-level pattern

The following example shows the decision flow. Replace the example proxy ranges with the addresses or CIDR ranges published by your own infrastructure provider. The sample intentionally fails closed for forwarded data and falls back to the direct peer.

<?php
/**
 * Return a validated client IP.
 *
 * $trustedProxyIps should contain exact proxy addresses after your
 * infrastructure has reduced its documented ranges. For larger networks,
 * use a CIDR-aware IP library or configure trust in your framework/web server.
 */
function clientIp(array $trustedProxyIps): ?string
{
    $direct = $_SERVER['REMOTE_ADDR'] ?? '';
    $directIp = filter_var($direct, FILTER_VALIDATE_IP);

    if ($directIp === false) {
        return null;
    }

    // No trusted proxy: the direct peer is the only usable address.
    if (!in_array($directIp, $trustedProxyIps, true)) {
        return $directIp;
    }

    $header = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
    if ($header === '') {
        return $directIp;
    }

    $candidates = array_map('trim', explode(',', $header));
    $valid = [];
    foreach ($candidates as $candidate) {
        $validated = filter_var($candidate, FILTER_VALIDATE_IP);
        if ($validated !== false) {
            $valid[] = $validated;
        }
    }

    if ($valid === []) {
        return $directIp;
    }

    // Choose the position required by your proxy's documented trust rule.
    // This example uses the left-most valid address.
    return $valid[0];
}

$ip = clientIp([
    '192.0.2.10',
    '2001:db8::10',
]);

The exact left-to-right or right-to-left choice depends on which hops your proxy controls and which it removes. Document that rule next to the code and test it with a request passing through every production hop. If you use Symfony, configure trusted proxies and call Request::getClientIp(); Symfony reads forwarded headers only when the proxy is trusted. See the Symfony proxy documentation.

Store, display, and compare addresses safely

Escape HTML output

Even though a correctly configured web server supplies an IP-looking value, output is still data. Use htmlspecialchars in HTML contexts:

Validate IP input before storing it, applying policy, or rendering it.
Validate IP input before storing it, applying policy, or rendering it.
<p>Your address: <?= htmlspecialchars($ip ?? 'unknown', ENT_QUOTES, 'UTF-8') ?></p>

Normalize for database storage

Validation preserves a usable textual address, but equivalent IPv6 spellings can differ. For reliable equality checks, normalize addresses to binary with inet_pton and store the result in a binary column, or use your database’s native IP type:

<?php
$packed = $ip !== null ? inet_pton($ip) : false;
if ($packed === false) {
    throw new InvalidArgumentException('Cannot store invalid IP');
}
// Bind $packed as a binary value in your database driver.

Keep a textual representation only when it helps operational searches or audit exports. Decide how long to retain addresses, who can access them, and whether your privacy requirements call for truncation or hashing.

Do not use an IP as authentication

An IP identifies a network endpoint, not a person. Mobile networks, NAT, corporate gateways, VPNs, and shared Wi-Fi can put many users behind one address. Use a real authentication factor for identity. Treat an address as one signal in abuse controls, never as the sole credential.

Useful validation policies

Goal Implementation Trade-off
Accept IPv4 and IPv6 FILTER_VALIDATE_IP Works for ordinary logging and display.
IPv4 only FILTER_VALIDATE_IP | FILTER_FLAG_IPV4 Rejects legitimate IPv6 clients.
IPv6 only FILTER_VALIDATE_IP | FILTER_FLAG_IPV6 Rejects IPv4 clients.
Public addresses only Add FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE Can reject valid internal or test traffic.
<?php
$raw = $_SERVER['REMOTE_ADDR'] ?? '';
$publicIp = filter_var(
    $raw,
    FILTER_VALIDATE_IP,
    FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
);
$publicIp = $publicIp === false ? null : $publicIp;

CLI, workers, and local development

When PHP runs from CLI, a queue worker, or a scheduled job, there is no browser request and therefore no meaningful REMOTE_ADDR. Use an explicit input parameter instead:

<?php
function validatedInputIp(?string $value): ?string
{
    $value = $value ?? '';
    $validated = filter_var($value, FILTER_VALIDATE_IP);
    return $validated === false ? null : $validated;
}

$ip = validatedInputIp($argv[1] ?? null);

For local testing, send a real HTTP request through your development server and inspect the value there. Do not assume that a command-line environment will populate web-server variables.

Common errors and fixes

Symptom Likely cause Fix
REMOTE_ADDR is missing The script runs from CLI, a worker, or a non-HTTP context. Pass the address explicitly or test through an HTTP server.
Every visitor has the same address A load balancer or reverse proxy is the direct peer. Configure trusted proxies and parse the provider’s forwarded header.
Rate limits are easy to bypass An unchecked X-Forwarded-For value controls the key. Ignore forwarded headers unless the direct peer is trusted and the chain is sanitized.
IPv6 addresses are rejected Code assumes dotted-quad IPv4 or uses an IPv4-only flag. Use FILTER_VALIDATE_IP without FILTER_FLAG_IPV4.
Address appears as an HTML injection Raw data is echoed into a page. Escape with htmlspecialchars.
Proxy parsing gives the wrong user The hop order or trust rule does not match the proxy documentation. Record the complete chain in a protected diagnostic log and implement the documented selection rule.
Private addresses disappear FILTER_FLAG_NO_PRIV_RANGE was applied globally. Use that flag only for a policy that truly requires public addresses.

Testing checklist

  • Test a direct IPv4 request.
  • Test a direct IPv6 request.
  • Test through every production proxy and load balancer.
  • Send a forged X-Forwarded-For header directly to the origin and confirm it is ignored.
  • Test an empty, malformed, and multi-value forwarded header.
  • Verify that rate limiting and authorization use the trusted result, not raw request headers.
  • Confirm logs and HTML responses escape the value.
  • Test CLI and worker paths where $_SERVER is unavailable.

Performance, reliability, and privacy

Reading $_SERVER and validating one address are constant-time operations and do not require a network lookup. Reverse DNS is slower, can fail, and can return misleading names; avoid it on the request path unless you have a specific operational need. If you need geolocation or reputation data, perform it asynchronously, cache results, and treat the result as advisory.

Proxy configuration is the reliability boundary. Keep trusted proxy ranges in deployment configuration rather than accepting them from request data. When infrastructure changes, update the ranges and the documented header format together. Log enough metadata to diagnose a bad chain, but protect those logs because IP addresses can be personal data.

Or skip the browser setup

If your goal is to capture a page image or PDF while inspecting page behavior, ScreenshotNeo provides a single HTTP endpoint. It removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and whether the request was billed.

See the ScreenshotNeo API documentation for the full set of options, including custom headers, cookies, user agents, authorization, JavaScript, CSS, waits, blocking rules, device presets, full-page capture, element capture, PDF output, caching, signed links, asynchronous jobs, bulk capture, and usage reporting.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await require('node:fs').promises.writeFile('shot.webp', image);

ScreenshotNeo includes an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

Is REMOTE_ADDR always the visitor’s real IP?

No. It is the direct peer seen by the web server. With a proxy, that peer may be the proxy itself.

Can I trust HTTP_X_FORWARDED_FOR?

Only when a trusted proxy controls the connection and sanitizes the header. A client can forge it when connecting directly to your application.

Should I store IPv4 and IPv6 differently?

Use validation that accepts both, then normalize with inet_pton or a database-native IP type if you need reliable comparisons.

Why does my local CLI script have no IP?

CLI execution has no HTTP client. Supply an address explicitly or send a request through a development web server.

Can an IP address identify a person?

Not reliably. Shared networks, NAT, VPNs, and changing mobile addresses mean it is an endpoint signal, not proof of identity.