Marius van Witzenburg We fight for our survival, we fight!

15Jun/110

How to grab the IP address from a remote user in PHP

The following example uses 'HTTP_X_FORWARDED_FOR' to detect if the request was forwarded by a proxy server or not.

if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
     $ip = $_SERVER['REMOTE_ADDR'];
}
echo $ip;

You could use this info for limiting happenings on your website to a several IP's or maybe an IP range if you need it.

For example you can use preg_match() to check if the IP is within the range you prefer:

if (preg_match('/^(192.168.3.1[0-9]|127.0.0.1|192.168.5.3)$/', $ip)) {
    echo "IP matches!";
}

Posted by mariusvw

Reacties (0) Trackbacks (0)

Nog geen reacties


Leave a comment

(required)

Nog geen trackbacks.