PHP 选项/信息 函数
在线手册:中文 英文
PHP手册

getenv

(PHP 4, PHP 5)

getenvGets the value of an environment variable

说明

string getenv ( string $varname )

Gets the value of an environment variable.

You can see a list of all the environmental variables by using phpinfo(). Many of these variables are listed within » RFC 3875, specifically section 4.1, "Request Meta-Variables".

参数

varname

The variable name.

返回值

Returns the value of the environment variable varname, or FALSE if the environment variable varname does not exist.

范例

Example #1 getenv() Example

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

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

参见


PHP 选项/信息 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: Gets the value of an environment variable

用户评论:

aladdin18 at hotmail dot com (21-Mar-2012 11:31)

Hi every one my name is AlAa

My problem with $_SERVER['remote_addr']

I'm not sure if I'm having a problem with the installation of PHP on the server or if there's something that I'm not doing right in the code, but I am trying to capture the IP address of anyone that is trying to log into a secure part of a site. Regardless of my IP address, when I do:

Code:

echo $_SERVER['remote_addr'];

It returns '192.168.1.1'. This is the first time I've written code that is being used on a Windows Server, so I don't know if that has anything to do with it.

I've run phpinfo(), and in the PHP Variables section, it shows "_SERVER["REMOTE_ADDR"]" : 192.168.1.1. Does this mean that the php.ini file is setup wrong, or am I missing something?

i am running my own server on windows 7 iis7.5 with php as fastcgi and i am behind a router with a dynamic ip not static and i am using
http://www.no-ip.com/ that give me a link to my router and i am opening 80 port in my router forwarding it to my id address 192.168.1.5 and i have tested a php file that contains
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
tested it using tor network that give me ip out of my network to test that file always give me the same result 192.168.1.1 i am trying to get IP address of the visitor and i asked someone of my friends to use this form it sends the same ip

i hope someone tells me what i am doing wrong and the solution for this problem

Thanks in advance

php at keith tyler dot com (08-Feb-2012 08:51)

All of the notes and examples so far have been strictly CGI.
It should not be understated the usefulness of getenv()/putenv() in CLI as well.

You can pass a number of variables to a CLI script via environment variables, either in Unix/Linux bash/sh with the "VAR='foo'; export $VAR" paradigm, or in Windows with the "set VAR='foo'" paradigm. (Csh users, you're on your own!) getenv("VAR") will retrieve that value from the environment.

We have a system by which we include a file full of putenv() statements storing configuration values that can apply to many different CLI PHP programs. But if we want to override these values, we can use the shell's (or calling application, such as ant) environment variable setting method to do so.

This saves us from having to manage an unmanageable amount of one-off configuration changes per execution via command line arguments; instead we just set the appropriate env var first.

eng.mrkto.com (29-Jul-2010 07:36)

This function is useful (compared to $_SERVER, $_ENV) because it searches $varname key in those array case-insensitive manner.
For example on Windows $_SERVER['Path'] is like you see Capitalized, not 'PATH' as you expected.
So just: <?php getenv('path') ?>

chuck dot reeves at gmail dot com (06-May-2010 07:59)

When writing CLI applications, not that any environment variables that are set in your web server config will not be passed through.  PHP will pass through system environment variables that are prefixed based off the safe_mode_allowed_env_vars directive in your php.ini

f dot hartmann2 at gmx dot net (23-Jul-2009 01:42)

A function returning the remote adress of the visiting browser could look like this:

<?php
function getIPfromXForwarded() {
   
$ipString=@getenv("HTTP_X_FORWARDED_FOR");
   
$addr = explode(",",$ipString);
    return
$addr[sizeof($addr)-1];
}
?>

Note that some adresses are followed by a whitespace and ip2long(getIPfromXForwarded()) would not return the expected result.

Make use of trim() in your scripts, either in the function itself, or the surrounding space of the caller.

Greetings

estarapapax at gmail dot com (19-Feb-2009 05:19)

This is a sample function for checking if your visitor comes from this certain country. This is especially useful for amateur webmasters who don't want to use sql databases.

Sample use of function:
<?php
if(check_coutry('http://www.domain.com/files/philippines.csv') === true)
      echo
'You are from the Philippines';
?>

Basically, you'll need CSV (or TXT) which lists the IP ranges of a certain country. Example (excerpt of the philippines.csv only):

58.69.0.0, 58.69.255.255
58.71.0.0, 58.71.127.255
61.9.0.0, 61.9.127.255
61.14.28.0, 61.14.28.63
61.14.41.136, 61.14.41.143
and so on until the end

You may obtain these CSV files in a number of websites out there. Be sure to update these CSV files regularly as these IP ranges change from time to time.

Here is the function:
<?php
function check_country($url_csv){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url_csv);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$str_fromfile = curl_exec($curl_handle);
curl_close($curl_handle);
$range = explode("\n", $str_fromfile);

$ip_addr = getenv(REMOTE_ADDR); //gets the IP of the visitor
$ip_byte = explode('.', $ip_addr);
$ip_number = (16777216 * (int) $ip_byte[0]) + (65536 * (int) $ip_byte[1]) + (256 * (int) $ip_byte[2]) + ((int) $ip_byte[3]);

for(
$i = 0; $range[$i] != NULL && $is_positive == NULL; $i++){ // the condition $line[$i] != NULL means that you should not put blank lines before the end of your CSV. The values should start at line 1.
   
$range[$i] = rtrim(ltrim($range[$i])); //you may remove this if you are sure the CSV doesnt contain whitespaces
   
$ends_addr = explode(',', $range[$i]); //for CSV (comma-separated values), comma is the separator. You may change this if your TXT uses different separator.
   
$ends_addr[0] = rtrim($ends_addr[0]); //again, you may remove this if your CSV is free from whitespaces
   
$ends_addr[1] = ltrim($ends_addr[1]); //yet, again
   
$start_ip_byte = explode('.', $ends_addr[0]);
   
$end_ip_byte = explode('.', $ends_addr[1]);
   
$start_ip_number = (16777216 * (int) $start_ip_byte[0]) + (65536 * (int) $start_ip_byte[1]) + (256 * (int) $start_ip_byte[2]) + ((int) $start_ip_byte[3]);
   
$end_ip_number = (16777216 * (int) $end_ip_byte[0]) + (65536 * (int) $end_ip_byte[1]) + (256 * (int) $end_ip_byte[2]) + ((int) $end_ip_byte[3]);
      
    if(
$ip_number >= $start_ip_number && $ip_number <= $end_ip_number)
           
$is_positive = 1;
}
  
    if(
$is_positive == 1)
        return
true;
    else
        return
false;
}
?>

sam at sambarrow dot com (13-Mar-2008 01:32)

SERVER_NAME is the name defined in the apache configuration.
HTTP_HOST is the host header sent by the client when using the more recent versions of the http protocol.

renko at <remove>virtual-life dot net (08-Nov-2004 02:40)

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"].

kyong (04-Feb-2004 09:06)

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.

daman at SPAM_BlockERmralaska dot com (08-Sep-2002 02:37)

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.

alex at acid-edge dot net (23-Jul-2002 06:32)

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

john-php at pc dot xs4all dot nl (16-Aug-2000 02:56)

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.