getenv

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

getenvRetourne la valeur d'une seule ou toutes les variables d'environnement

Description

getenv(?string $name = null, bool $local_only = false): string|array|false

Retourne la valeur d'une seule ou toutes les variables d'environnement.

Vous pouvez voir une liste complète des variables d'environnement en utilisant la fonction phpinfo(). Vous pouvez trouver la signification de chacune d'entre elles en consultant la » RFC 3875, en particulier la section 4.1 "Request Meta-Variables".

Liste de paramètres

name

Le nom de la variable en tant que chaîne de caractères ou null.

local_only

Lorsqu'il est défini sur true, seules les variables d'environnement locales sont renvoyées, définies par le système d'exploitation ou putenv. Cela n'a d'effet que lorsque name est une chaîne de caractères.

Valeurs de retour

Retourne la valeur de la variable d'environnement name, ou false si la variable d'environnement name n'existe pas. Si name est omit, toutes les variables d'environnement sont retournée en tant qu'un tableau associatif.

Historique

Version Description
8.0.0 Le name est désormais nullable.
7.1.0 name peut désormais être omit pour récupérer un tableau associatif de toutes les variables d'environnement.
7.0.9 Le paramètre local_only a été ajouté.

Exemples

Exemple #1 Exemple avec getenv()

<?php
// Exemple d'utilisation de getenv()
$ip = getenv('REMOTE_ADDR');

// Ou utilisez simplement une Superglobale ($_SERVER ou $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];

// Obtenir en toute sécurité la valeur d'une variable d'environnement,
// ignorant si elle a été définie par un SAPI ou a été modifiée avec putenv
$ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR')
?>

Notes

Avertissement

Si PHP est exécuté dans un SAPI tel que Fast CGI, cette fonction retournera toujours la valeur d'une variable d'environnement définit par le SAPI, même si putenv() a été utilisé pour définir une variable d'environnement locale avec le même nom. Le paramètre local_only doit être utilisé pour retourner les valeurs de variables d'environnements définit localement.

Voir aussi

add a note add a note

User Contributed Notes 15 notes

up
43
Anonymous
5 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"
up
4
jcastromail at yahoo dot es
3 years 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.
up
29
eng.mrkto.com
13 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') ?>
up
6
yw()beeznest!com
7 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.
up
14
php at keith tyler dot com
12 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.
up
3
larby dot robert at gmail dot com
5 years ago
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
up
8
kyong
20 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.
up
2
Anonymous
4 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().
up
3
pritisn at gmail dot com
8 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.
up
4
hello at jabran dot me
8 years ago
Beware that when using this function with PHP built-in server – i.e. php -S localhost:8000 – it will return boolean FALSE.
up
1
chuck dot reeves at gmail dot com
13 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
up
0
sam at sambarrow dot com
16 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.
up
-12
jaraco at jaraco dot com
6 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')
up
-37
f dot hartmann2 at gmx dot net
14 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
up
-42
renko at <remove>virtual-life dot net
19 years ago
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"].
To Top