Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : PHP Options&Information : getenv

getenv

Gets the value of an environment variable (PHP 4, PHP 5)
string getenv ( string varname )

Example 1840. getenv() Example

<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>

Related Examples ( Source code ) » getenv









Code Examples / Notes » getenv

roland

You need also to know that $_SERVER['SERVER_NAME'] and surely $_SERVER['PHP_SELF'] are fakeable by sending wrong HTTP headers (hint: "Host:" will become SERVER_NAME in your PHP scripts). For PHP_SELF you may want to use SCRIPT_NAME instead.
You may want to use this little code to continue using PHP_SELF:
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME']; $PHP_SELF = $_SERVER['PHP_SELF']
The last one is for people who cannot switch "register_global" off.
There is now "secure" replacement for SERVER_NAME available. Sometimes SERVER_ADDR (which not fakeable) might be handy but in some situations not. If you need a valid entry in SERVER_NAME validate it with a regular expressions. See regexlib.com for such expressions.


sorry

To show a use of getenv("QUERY_STRING")....
suppose you have a site with frames...  the frames create the "interface", and one frame called "main" has an active document...  now, suppose you made a page.php3 which took an argument "pg" and spit out the framesets necessary, with "main" frame containing whatever "pg" is...  so now you can bring up any page in your site with page.php3?pg=test.html
now, take this one step further, and suppose you want outside links to point to php3 pages which takes parameters, ON your site...  but you still want them to appear in frames, so what do you do?  well, if "ok.php3" was the page you wanted to show, and it was requested as "ok.php3?some=params&go=here", then the very thing in the beginning of ok.php3 could be
if (!isset($inframe)) {
header("Location: http://yoursite/page.php3?pg=".urlencode("inframes=1&").getenv("QUERY_STRING"));
exit;
}
Now... you might ask, how in the world did I come up with THAT?  Well, perhaps it was because I came here not able to remember which environment variable held the query string...


joenema

This is just a reply to Anders Winther's fool-proof IP address fetcher.
What he has is good, but uses a lot of superfluous lines. Basically, he could have done this:
function getIP() {
$ip;
if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
else $ip = "UNKNOWN";
return $ip;
}
Do you see how those numerous lines of code compressed into a few lines?


kev

This came in really handy, I looked everywhere on the Internet for a simple answer to this and the
solution turned out to be pleasantly simple.
Let's say you have a secure server. You want everyone to use this secure server every time they access.
But, you don't want to cut off http access entirely because people do forget to type that in the address bar.
Just stick this at the top of your PHP script or in your header file:
if (!$_SERVER["HTTPS"]) {
       header("Location: https://your.secure.server.com/\n\n");
       exit;
}
I am testing this now but so far it works great, how would all of you all normally handle this
(without forcing .htaccess passwords and doing the redirect that way, just for general users)?
I tried web searches along the lines of "apache http https in different directories" and
"force https access redirect apache" but nothing really worked as simply as this did.


renko

The function 'getenv' does not work if your Server API is ASAPI (IIS).
So, try to don't use getenv('REMOTE_ADDR'), but $_SERVER["REMOTE_ADDR"].


john-php

Note that the X-Forwarded for header might contain multiple addresses, comma separated, if the request was forwarded through multiple proxies.
Finally, note that any user can add an X-Forwarded-For header themselves. The header is only good for traceback information, never for authentication. If you use it for traceback, just log the entire X-Forwarded-For header, along with the REMOTE_ADDR.


alex

Note that some caches seem to send the client-ip header *backwards*. be careful :)

svpe

I've read all the comments here.
Most of you trust that HTTP_X_FORWARDED_FOR is the real ip address of the user.
But it can easily be faked by sending a wrong HTTP request.
REMOTE_ADDR does contain the 'real' ip address (maybe of the proxy server but it cannot be faked as easy as X_FORWARDED_FOR)
So if you rely on checking the visitor by it's ip address validate _both_ $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_X_FORWARDED_FOR'].


mkaman

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);
}


shane

I am just starting to try to tackle this issue of getting the real ip address.
One flaw I see in the preceding notes is that none will bring up a true live ip address when the first proxy is behind a nat router/firewall.
I am about to try and nut this out but from the data I see so far the true ip address (live ip of the nat router) is included in $_SERVER['HTTP_CACHE_CONTROL'] as bypass-client=xx.xx.xx.xx
$_SERVER['HTTP_X_FORWARDED_FOR'] contains the proxy behind the nat router.
$_SERVER['REMOTE_ADDR'] is the isp proxy (from what I read this can be a list of proxies if you go through more than one)
I am not sure if bypass-client holds true when you get routed through several proxies along the way.


mayday

daniele_dll:
Your function hase a bug!
If You check this IPs:
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.2,127.0.0.3';
the function will return this:
Array
(
   [0] => 127.0.0.1
   [1] => 127.0.0.3
)
Yes, the first element from 'HTTP_X_FORWARDED_FOR' is lost.
The only fixes you need to make is to move down one line.
This is the correct way:
<?php
function get_ip_list() {
   $tmp = array();
   if  (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strpos($_SERVER['HTTP_X_FORWARDED_FOR'],',')) {
       $tmp +=  explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
   } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$tmp[] = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
   $tmp[] = $_SERVER['REMOTE_ADDR'];
   return $tmp;
}
?>


daman

Be careful using HTTP_X_FORWARDED_FOR in conditional statements collecting the IP address. Sometimes the user's LAN address will get forwarded, which of course is pretty worthless by itself.

kyong

As you know, getenv('DOCUMENT_ROOT') is useful.
However, under CLI environment(I tend to do quick check
if it works or not), it doesn't work without modified php.ini
file. So I add "export DOCUMENT_ROOT=~" in my .bash_profile.


Change Language


Follow Navioo On Twitter
assert_options
assert
dl
extension_loaded
get_cfg_var
get_current_user
get_defined_constants
get_extension_funcs
get_include_path
get_included_files
get_loaded_extensions
get_magic_quotes_gpc
get_magic_quotes_runtime
get_required_files
getenv
getlastmod
getmygid
getmyinode
getmypid
getmyuid
getopt
getrusage
ini_alter
ini_get_all
ini_get
ini_restore
ini_set
main
memory_get_peak_usage
memory_get_usage
php_ini_scanned_files
php_logo_guid
php_sapi_name
php_uname
phpcredits
phpinfo
phpversion
putenv
restore_include_path
set_include_path
set_magic_quotes_runtime
set_time_limit
sys_get_temp_dir
version_compare
zend_logo_guid
zend_thread_id
zend_version
eXTReMe Tracker