How to Find the Client IP Address in PHP
In PHP, read $_SERVER['REMOTE_ADDR'] for the connection address reported by the web server. With a direct connection, it is the address the server sees for the client. Behind a reverse proxy or load balancer, it may be the intermediary’s address. Check how the web server handles addresses in that setup.
What REMOTE_ADDR represents
$_SERVER is an array containing request information provided to PHP by the web server. REMOTE_ADDR is the reported remote address. The key may be absent when you run php ip.php in the command line, because there is no web request. The example handles a missing value with ?? and validates IPv4 and IPv6 syntax with FILTER_VALIDATE_IP. Validation alone does not establish where the address came from or identify the user.
<?php
header('Content-Type: text/plain; charset=UTF-8');
header('Cache-Control: no-store');
$address = $_SERVER['REMOTE_ADDR'] ?? null;
$ip = is_string($address)
? filter_var($address, FILTER_VALIDATE_IP)
: false;
if ($ip === false) {
echo 'IP address unavailable.', PHP_EOL;
exit;
}
echo $ip, PHP_EOL;
Check the IPv4 address locally
Save the code as ip.php in UTF-8 and run the command from the same folder. Open http://127.0.0.1:8000/ip.php in your browser to see 127.0.0.1 on its own line. This loopback address points to the same computer. Press Ctrl+C in the terminal to stop the server. ::1 is the corresponding example for a connection over IPv6 loopback.
php -S 127.0.0.1:8000
Which address appears behind a proxy?
A reverse proxy can open a new connection to the backend on behalf of the browser. If you repeatedly see an internal address, check whether it belongs to the proxy. If you need the original connection address, configure the trusted intermediaries in a server feature such as Apache’s mod_remoteip or Nginx’s Real IP module and test what the server passes to PHP. Using the first X-Forwarded-For entry directly can put the wrong address into logs or access rules.
Use IP addresses in production
Use the sample page for local diagnostics and retain only the values you need in production logs. Dumping $_SERVER can reveal unrelated request headers and internal paths. Multiple people can share one public address, and one person’s address can change. Use account authentication for identity checks.




