note 27678 deleted from reserved.variables by sniper
| From: | sniper@php.net | Date: | Tue, 21 Oct 2003 19:45:34 +0000 |
| Subject: | note 27678 deleted from reserved.variables by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-59080@lists.php.net to get a copy of this message | ||
Note Submitter: s3v3n_0f_n1n3@hotmail.com
----
Lately i was working on a script that always fetches the right ip adress. Funny enough the
HTTP_CLIENT_IP isn't stored in $_ENV, but in $_SERVER, while it can be fetched with getenv();.
Because this script took some time creating it, i wish to share it with the public:
<?php
function fetchip() {
//get useful vars:
$client_ip = $_SERVER['HTTP_CLIENT_IP'];
$x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
$remote_addr = $_SERVER['REMOTE_ADDR'];
// then the script itself
if (!empty ($client_ip) ) {
$ip_expl = explode('.',$client_ip);
$referer = explode('.',$remote_addr);
if($referer[0] != $ip_expl[0]) {
$ip=array_reverse($ip_expl);
$return=implode('.',$ip);
} else {
$return = $client_ip;
};
} elseif (!empty($x_forwarded_for) ) {
if(strstr($x_forwarded_for,',')) {
$ip_expl = explode(',',$x_forwarded_for);
$return = end($ip_expl);
} else {
$return = $x_forwarded_for;
};
} else {
$return = $remote_addr;
};
unset ($client_ip,$x_forwarded_for,$remote_addr,$ip_expl,);
return $return;
};
?>
The ip adress can be fetched just by using $ip=fetchip();
I wish to note that the entire script under if (!empty ($client_ip) ) { is to makre sure the ip
adress isn't backwards(which seems to happen sometimes, like with NTL users). This will not
work if the first and last number in the IP Adress is the same.