Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

8.20. Reading Environment Variables

Problem

You want to get the value of an environment variable.

Solution

Read the value from the $_ENV superglobal array:

$name = $_ENV['USER'];

Discussion

Environment variables are named values associated with a process. For instance, in Unix, you can check the value of $_ENV['HOME'] to find the home directory of a user:

print $_ENV['HOME']; // user's home directory
/home/adam

Early versions of PHP automatically created PHP variables for all environment variables by default. As of 4.1.0, php.ini-recommended disables this because of speed considerations; however php.ini-dist continues to enable environment variable loading for backward compatibility.

The $_ENV array is created only if the value of the variables_order configuration directive contains E. If $_ENV isn’t available, use getenv( ) to retrieve an environment variable:

$path = getenv('PATH');

The getenv( ) function isn’t available if you’re running PHP as an ISAPI module.

See Also

Recipe 8.22 on setting environment variables; documentation on getenv( ) at http://www.php.net/getenv; information on environment variables in PHP at http://www.php.net/reserved.variables.php#reserved.variables.environment.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata