superkytoz superkytoz - 1 year ago 41
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.


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

if ($_SERVER["SERVER_ADDR"] === "") {
  // Running on local development server

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

In .htaccess


In code:

if (get_env("MY_ENVIRONMENT") === "live") {
  // Running in live environment