Recipe 8.14. Reading Environment Variables

8.14.1. Problem

You want to get the value of an environment variable.

8.14.2. Solution

Read the value from the $_ENV auto-global array as shown in Example 8-33.

Reading an environment variable

<?php $name = $_ENV['USER']; ?>

8.14.3. 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, as shown in Example 8-37.

Reading another environment variable

<?php print $_ENV['HOME']; // user's home directory ?>

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 $_ENV 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, as shown in Example 8-35.

Using getenv( )

<?php $path = getenv('PATH'); ?>

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

8.14.4. See Also

Recipe 8.15 on setting environment variables; documentation on getenv( ) at; information on environment variables in PHP at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: