简体   繁体   中英

Setting PHP variables in httpd.conf?

I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.

So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?

$database = 'live';
if (some staging environment variable is true) {
    $database = 'testing'; // and not live
}

If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile

Hope this makes sense

many thanks

Ian

Yep...you can do this:

SetEnv DATABASE_NAME testing

and then in PHP:

$database = $_SERVER["DATABASE_NAME"];

or

$database = getenv("DATABASE_NAME");

You can set an environment variable and retrieve it with PHP.

In httpd.conf:

SetEnv database testing

In your PHP:

if (getenv('database') == 'testing') {

or

if ($_SERVER['database'] == 'testing') {

Did you tried to use the .htaccess file? You could override the php.ini values using it.

Just put the .htaccess file into your htdocs directory:

php_value name value

Futher information:

I would not set an environment variable, as this is also visible in default script outputs like PhpInfo();

just use a php_value in your .htaccess just above the htdocs folder and you're done and safe :)

The problem with .htaccess is that it is part of the code base tree. And the code base tree is part of VC/SVN. Hence any change in local/dev gets moved to production. Keeping the env variable setting in httpd.conf saves you the effort of being careful about not accidentally overwriting the server vs dev flag. Unless of course you want to do with IP address or host name, both of which are not scalable approaches.

I was also looking at this type of solution. What I found is this, under Apache you can use the SetEnv KeyName DataValue in the http.conf and in IIS you can use Fast CGI Settings >> Edit... >> Environment Variables >> ... and add KeyName, DataValue .

This in turn allows the PHP $var = $_SERVER["KeyName"]; to be set to the DataValue and used as needed under both IIS and Apache consistently.

I know this is a strange use case. I use WAMP at work and MAMP at home so it is nice to be able to work the same way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM