PHP $_ENV


Introduction

$_ENV is another superglobal associative array in PHP. It stores environment variables available to current script. $HTTP_ENV_VARS also contains the same information, but is not a superglobal, and now been deprecated.

Environment variables are imported into global namespace. Most of these variables are provided by the shell under which PHP parser is running. Hence, list of environment variables may be different on different platforms.

This array also includes CGI variables in case whether PHP is running as a server module orCGI processor.

PHP library has getenv()function to retrieve list of all environment variables or value of a specific environment variable

getenv

Following script displays values of all available environment variables

<?php
$arr=getenv();
foreach ($arr as $key=>$val)
echo "$key=>$val
";
?>

To obtain value of specific variable use its name as argument for getenv() function

Example

 Live Demo

<?php
echo "Path: " . getenv("PATH");
?>

Output

Browser will display result similar to following

Path: /usr/local/bin/factor:/root/.sdkman/candidates/kotlin/current/bin:/usr/GNUstep/System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/scriba/bin:/usr/local/smlnj/bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/local/dart/bin:/usr/libexec/sdcc:/usr/local/icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/pash/Source/PashConsole/bin/Debug/:.:/root/.sdkman/candidates/kotlin/current/bin:/usr/bin:/sbin:/bin

PHP also has putenv() function to create a new environment variable. The environment variable will only exist for the duration of the current request.

Changing value of certain environment variables should be avoided. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

The safe_mode_protected_env_vars directive in php.ini contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv().

putenv

Example

 Live Demo

<?php
putenv("PHP_TEMPUSER=GUEST");
echo "Temp user: " . getenv("PHP_TEMPUSER");
?>

Output

Browser will display result as following

Temp user: GUEST

Updated on: 21-Sep-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements