How to get the visitor's IP address
Short answer
The connection address is in $_SERVER['REMOTE_ADDR']:
<?php
echo $_SERVER['REMOTE_ADDR'];Behind a proxy or load balancer
If the site sits behind a proxy, REMOTE_ADDR is the proxy's address, and the real one is passed in the X-Forwarded-For header. Read it only when the request came from your proxy: a visitor can forge the header.
<?php
$trustedProxies = ['10.0.0.1'];
$ip = $_SERVER['REMOTE_ADDR'];
if (in_array($ip, $trustedProxies, true) && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
}Validating the address
filter_var() checks that a string is a valid IP address:
<?php
var_dump(filter_var('192.168.1.10', FILTER_VALIDATE_IP) !== false);
var_dump(filter_var('999.1.1.1', FILTER_VALIDATE_IP) !== false);Output:
bool(true)
bool(false)Functions used in this recipe
- filter_var — Validates or sanitises a value by a given rule.
- explode — Splits a string into an array by a separator.
- trim — Removes whitespace and other characters from both ends of a string.