note 41833 added to function.getenv
| From: | mkamanataldeafuturadotcom at rn2 dot php dot net | Date: | Fri, 23 Apr 2004 10:33:41 +0000 |
| Subject: | note 41833 added to function.getenv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-68621@lists.php.net to get a copy of this message | ||
I think there is a better way to determine a correct ip. This is based in the fact that the private
ip's for lan use are described in RFC 1918.
So all we have to do is get an ordered array of ip's and take the first ip that doesn't is
a private ip.
//List of the private ips described in the RFC. You can easily add the
//127.0.0.0/8 to this if you need it.
$ip_private_list=array(
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16"
);
//Determine if an ip is in a net.
//E.G. 120.120.120.120 in 120.120.0.0/16
//I saw this in another post in this site but don't remember where :P
function isIPInNet($ip,$net,$mask) {
$lnet=ip2long($net);
$lip=ip2long($ip);
$binnet=str_pad( decbin($lnet),32,"0","STR_PAD_LEFT" );
$firstpart=substr($binnet,0,$mask);
$binip=str_pad( decbin($lip),32,"0","STR_PAD_LEFT" );
$firstip=substr($binip,0,$mask);
return(strcmp($firstpart,$firstip)==0);
}
//This function check if a ip is in an array of nets (ip and mask)
function isIpInNetArray($theip,$thearray)
{
$exit_c=false;
#print_r($thearray);
foreach ( $thearray as $subnet ) {
list($net,$mask)=split("/",$subnet);
if(isIPInNet($theip,$net,$mask)){
$exit_c=true;
break;
}
}
return($exit_c);
}
//Building the ip array with the HTTP_X_FORWARDED_FOR and
//REMOTE_ADDR HTTP vars.
//With this function we get an array where first are the ip's listed in
//HTTP_X_FORWARDED_FOR and the last ip is the REMOTE_ADDR.
//This is inspired (copied and modified) in the function from daniel_dll.
function GetIpArray()
{
$cad="";
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND
$_SERVER['HTTP_X_FORWARDED_FOR']!="")
$cad=$_SERVER['HTTP_X_FORWARDED_FOR'];
if(isset($_SERVER['REMOTE_ADDR']) AND
$_SERVER['REMOTE_ADDR']!="")
$cad=$cad.",".$_SERVER['REMOTE_ADDR'];
$arr= explode(',',$cad);
return $arr;
}
//We check each ip in the array and we returns the first that is not a
//private ip.
function getIp()
{
global $ip_private_list;
$ip = "unknown";
$ip_array=getIpArray();
foreach ( $ip_array as $ip_s ) {
if( $ip_s!="" AND !isIPInNetArray($ip_s,$ip_private_list)){
$ip=$ip_s;
break;
}
}
return($ip);
}
----
Manual Page -- http://www.php.net/manual/en/function.getenv.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41833
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41833&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41833&report=yes
Search -- http://master.php.net/manage/user-notes.php