总有人间一两风,填我十万八千梦

PHP getenv 用法 手册 | 示例代码

PHP开发手册 归档 299℃ 0评论

getenv

(PHP 4, PHP 5, PHP 7)

getenv获取一个环境变量的值

说明

getenv ( string $varname [, bool $local_only = FALSE ] ) : string
getenv ( void ) : array

获取一个环境变量的值。

使用 phpinfo() 你可以看到所有环境变量的列表。 这些变量很多都在 » RFC 3875 的范围之内, 尤其是章节4.1,"Request Meta-Variables"。

参数

varname

变量名。

local_only

设置为 true 以仅返回本地环境变量(由操作系统或 putenv() 设置)。

返回值

返回环境变量 varname 的值, 如果环境变量 varname 不存在则返回 FALSE。 如果省略 varname,则所有环境变量都将作为关联数组 array 返回。

更新日志

版本 说明
7.1.0 现在可以省略 varname 来检索所有环境变量的关联数组 array
5.5.38, 5.6.24, 7.0.9 添加 local_only 参数。

注释

Warning

如果 PHP 在诸如 Fast CGI 之类的 SAPI 中运行,则此函数将始终返回由 SAPI 设置的环境变量的值,即使已使用 putenv() 来设置同名的本地环境变量。使用 local_only 参数返回本地设置的环境变量的值。

范例

Example #1 getenv() 例子

<?php
// getenv() 使用示例
$ip getenv('REMOTE_ADDR');

// 或简单仅使用全局变量($_SERVER 或 $_ENV)
$ip $_SERVER['REMOTE_ADDR'];

// 安全地获取环境变量,忽略通过 SAPI 或 putenv 修改的值
$ip getenv('REMOTE_ADDR'true) ?: getenv('REMOTE_ADDR')
?>

参见

用户贡献的笔记

Anonymous

Contrary to what eng.mrkto.com said, getenv() isn't always case-insensitive. On Linux it is not:

<?php
var_dump
(getenv('path')); // bool(false)
var_dump(getenv('Path')); // bool(false)
var_dump(getenv('PATH')); // string(13) "/usr/bin:/bin"

eng.mrkto.com

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') ?>

larby dot robert at gmail dot com

From PHP 7.1 => getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.

Source: http://php.net/manual/en/migration71.changed-functions.php

yw()beeznest!com

As noted on httpoxy.org, getenv() can confuse you in having you believe that all variables come from a "safe" environment (not all of them do).

In particular, $_SERVER['HTTP_PROXY'] (or its equivalent getenv('HTTP_PROXY')) can be manually set in the HTTP request header, so it should not be considered safe in a CGI environment.

In short, try to avoid using getenv('HTTP_PROXY') without properly filtering it.

php at keith tyler dot com

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.

Anonymous

It is worth noting that since getenv('MY_VARIABLE') will return false when the variable given is not set, there is no direct way to distinguish between a variable that is unset and one that is explicitly set to the value bool(false) when using getenv(). 
This makes it somewhat tricky to have boolean environment variables default to true if unset, which you can work around either by using "falsy" values such as 0 with the strict comparison operators or by using the superglobal arrays and isset().

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.

hello at jabran dot me

Beware that when using this function with PHP built-in server – i.e. php -S localhost:8000 – it will return boolean FALSE.

pritisn at gmail dot com

for quick check of getenv() adding a new env variable -
if you add a new env variable, make sure not only apache but xampp is also restarted.
Otherwise getenv() will return false for the newly added env variable.

chuck dot reeves at gmail dot com

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

sam at sambarrow dot com

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.

jaraco at jaraco dot com

The example on how to fallback produces a syntax error on PHP 5.2:

-bash-3.2$ cat test.php
<?php

$ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR')

?>

-bash-3.2$ /web/cgi-bin/php5 test.php
Content-type: text/html

<br />
<b>Parse error</b>:  syntax error, unexpected ':' in <b>/home/content/25/11223125/test.php</b> on line <b>3</b><br />

On PHP 5.2, one must write

$ip = getenv('REMOTE_ADDR', true) ? getenv('REMOTE_ADDR', true) : getenv('REMOTE_ADDR')

f dot hartmann2 at gmx dot net

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

renko at <remove>virtual-life dot net

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

转载请注明:悠然品鉴 » PHP getenv 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址