tags:

views:

1842

answers:

4

Hi,

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

+10  A: 

Yep...you can do this:

SetEnv DATABASE_NAME testing

and then in PHP:

$database = $_SERVER["DATABASE_NAME"];

or

$database = getenv("DATABASE_NAME");
JW
Ahem, pardon me, shouldn't that read $_ENV["DATABASE_NAME"]?
Brent.Longborough
Yep...thanks. I corrected it.
JW
As far as i know it should be $_SERVER['DATABASE_NAME'] instead of $_ENV.Tested it here on php 5.2 debian and the vars aren't inserted in $_ENV but in $_SERVER
ChrisR
Looks like you're right. $_ENV works on the command line, but it doesn't seem to get populated when running under Apache.
JW
+2  A: 

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') {

Christian Lescuyer
+5  A: 

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:

Gravstar
Doing this through htaccess sounds like a much better idea than httpd.conf.
Alex
Disagree; doing it in the vhost configuration section is better, as it means that you can disable .htaccess entirely, which is a performance gain for apache as it doesn't have to check for a .htaccess file for every request.
El Yobo
A: 

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 :)

SchizoDuckie