14

Is my understand regarding superglobal arrays $_ENV and $_SERVER correct ?

$_ENV: Contains information about environment variables
$_SERVER: Contains information about the server

$_ENV is accessible from both web server and on the command line
$_SERVER is accessible through only web server, not on the command line

Muhammed Khalander
  • 285
  • 1
  • 5
  • 11

2 Answers2

5

Put this code in a file:

<?php
header('Content-Type: text/plain');

echo('$_ENV[] = '); print_r($_ENV);
echo('$_SERVER[] = '); print_r($_SERVER);

Run it using the command line and the web server and see what you get.

To my surprise, on my computer $_ENV[] is empty on both setups and $_SERVER[] contains the environment variables when the code runs from the CLI.

In general, the outcome depends a lot on the operating system and web server you use.

axiac
  • 68,258
  • 9
  • 99
  • 134
  • `$_ENV` exists for the duration of the current session. Since your script doesn't start a new session the superglobal is empty. – s3c Dec 07 '20 at 12:08
  • That is [`$_SESSION`](https://www.php.net/manual/en/reserved.variables.session.php), not `$_ENV`. – axiac Dec 07 '20 at 12:30
  • I believed this statement: "These environment variables will not last outside the session in which they were created." from [mediatemple](https://mediatemple.net/community/products/grid/204643130/using-environment-variables-in-php), but I can't seem to find it in [`$_ENV` documentation](https://www.php.net/manual/en/reserved.variables.environment.php). Sorry about that. First comment in said docs explains it: "If $_ENV is empty, but you still see the variables with getenv(), check http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string." – s3c Dec 07 '20 at 14:17
  • 1
    That article uses the word "request" with a different meaning, not its common meaning of "web session". It seems it means the execution of the script, which should be a separate execution for each request. It is not recommended to use `$_ENV` as a regular PHP variable. Its purpose is to store values that are set from outside the PHP environment (either from the process environment of the web server or of the shell that launched the PHP CLI). – axiac Dec 07 '20 at 14:28
4

You are half right :)

$_ENV contains information about the environment which the PHP interpreter is running in.

Both $_ENV and $_SERVER are accessible from command line

Sean
  • 1,304
  • 11
  • 26