superkytoz superkytoz - 1 year ago 54
PHP Question

Connect to database depending on host

I want to connect to my database depending if I'm on localhost or on the webapp that's hosted online. But I don't know how to do that. Anyone got some idea's or examples?

Because now I have to comment out my line of code everytime I'm deploying my web app to the host and use the database credentials for the online host.

Answer Source

1) Inspect the $_SERVER superglobal and check if the code is running locally.

<?php 
if ($_SERVER["SERVER_ADDR"] === "127.0.0.1") {
  // Running on local development server
}

2) Set and read environment variable that identifies where the code is running

In .htaccess

SetEnv MY_ENVIRONMENT "live"

In code:

<?php 
if (get_env("MY_ENVIRONMENT") === "live") {
  // Running in live environment
}