Recipe 8.15. Setting Environment Variables


8.15.1. Problem

You want to set an environment variable in a script or in your server configuration. Setting environment variables in your server configuration on a host-by-host basis allows you to configure virtual hosts differently.

8.15.2. Solution

To set an environment variable in a script, use putenv( ), as in Example 8-36.

Setting an environment variable

<?php putenv('ORACLE_SID=ORACLE'); // configure oci extension ?>

To set an environment variable in your Apache httpd.conf file, use SetEnv as shown in Example 8-37. Note that variables set this way show up in the PHP auto-global array $_SERVER, not $_ENV.

Setting an environment variable in Apache configuration

<?php SetEnv DATABASE_PASSWORD password ?>

8.15.3. Discussion

An advantage of setting variables in httpd.conf is that you can set more restrictive read permissions on it than on your PHP scripts. Since PHP files need to be readable by the web server process, this generally allows other users on the system to view them. By storing passwords in httpd.conf, you can avoid placing a password in a publicly available file. Also, if you have multiple hostnames that map to the same document root, you can configure your scripts to behave differently based on the hostnames.

For example, you could have members.example.com and guests.example.com. The members version requires authentication and allows users additional access. The guests version provides a restricted set of options, but without authentication. Example 8-38 shows how this could work.

Adjusting behavior based on an environment variable

<?php $version = $_SERVER['SITE_VERSION']; // redirect to http://guest.example.com, if user fails to sign in correctly if ('members' == $version) {     if (!authenticate_user($_POST['username'], $_POST['password'])) {         header('Location: http://guest.example.com/');         exit;     } } include_once "${version}_header"; // load custom header

8.15.4. See Also

Recipe 8.14 on getting the values of environment variables; documentation on putenv( ) at http://www.php.net/putenv; information on setting environment variables in Apache at http://httpd.apache.org/docs/mod/mod_env.html.




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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net