Penggunaan fungsi SYSTEM.GETENV pada PHP

Saya tahu bahwa komentar dalam dokumen mengatakan bahwa getenv tidak sensitif-huruf, tapi itu bukan perilaku yang saya lihat:

Show
> env FOO=bar php -r 'print getenv("FOO") . "\n";'
bar
> env FOO=bar php -r 'print getenv("foo") . "\n";'

> env foo=bar php -r 'print getenv("foo") . "\n";'
bar
> env foo=bar php -r 'print getenv("FOO") . "\n";'

> php --version
PHP 5.4.24 (cli) (built: Jan 24 2014 03:51:25)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

Melihat kode sumber untuk fungsi getenv, ini karena ada tiga cara yang PHP dapat mengambil variabel lingkungan:

  1. Melalui sapi_getenv (Mis. Jika itu mendapatkan variabel lingkungan dari Apache)
  2. Jika di Windows, dari GetEnvironmentVariableA.
  3. Jika pada non-Windows, dari fungsi getenv disediakan oleh libc.

Sejauh yang saya tahu, satu-satunya waktu ketika ia akan berperilaku case-insensitive adalah pada Windows karena itulah bagaimana variabel lingkungan Windows berperilaku API. Jika Anda menggunakan Linux, BSD, Mac, dll maka getenv masih peka huruf besar-kecil.

Seperti yang disebutkan oleh mario , $_ENV Tidak selalu diisi karena berbagai konfigurasi variables_order Jadi sebaiknya jika Anda menghindari $_ENV Jika Anda tidak mengontrol konfigurasi server.

Jadi, untuk kode PHP yang paling portabel:

  1. Gunakan getenv.
  2. Gunakan huruf yang benar untuk nama variabel lingkungan.

(PHP 4, PHP 5, PHP 7, PHP 8)

getenvGets the value of an environment variable

Description

getenv(string $varname, bool $local_only = false): string|false

getenv(): array

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

Parameters

varname

The variable name.

local_only

Set to true to only return local environment variables (set by the operating system or putenv).

Return Values

Returns the value of the environment variable varname, or false if the environment variable varname does not exist. If varname is omitted, all environment variables are returned as associative array.

Changelog

VersionDescription
7.1.0 The varname can now be omitted to retrieve an associative array of all environment variables.
7.0.9 The local_only parameter has been added.

Examples

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'];// Safely get the value of an environment variable, ignoring whether 
// or not it was set by a SAPI or has been changed with putenv
$ip getenv('REMOTE_ADDR'true) ?: getenv('REMOTE_ADDR')
?>

Notes

Warning

If PHP is running in a SAPI such as Fast CGI, this function will always return the value of an environment variable set by the SAPI, even if putenv() has been used to set a local environment variable of the same name. Use the local_only parameter to return the value of locally-set environment variables.

See Also

  • putenv() - Sets the value of an environment variable
  • apache_getenv() - Get an Apache subprocess_env variable
  • Superglobals

Anonymous

4 years ago

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"

jcastromail at yahoo dot es

1 year ago

I did a benchmark about env.

constants :
0.00067687034606934 ms
getenv :
0.056761026382446 ms

(less is better)

https://github.com/eftec/php-benchmarks#define--const--env

And, in Windows at leat, reading the env value is considerably slow (in comparison with a constant), so PHP doesn't cache the information and asks to the OS the env value per call.

So, if you are calling once per request, then there is not a problem. However, if you are calling it many times per request, then it could affects the performance.

eng.mrkto.com

12 years ago

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

php at keith tyler dot com

10 years ago

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.

yw()beeznest!com

6 years ago

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.

kyong

18 years ago

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.

pritisn at gmail dot com

7 years ago

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.

hello at jabran dot me

7 years ago

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

sam at sambarrow dot com

14 years ago

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.

Anonymous

3 years ago

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().

chuck dot reeves at gmail dot com

12 years ago

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

jaraco at jaraco dot com

5 years ago

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

13 years ago

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