Reputation: 1279
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.
Upvotes: 2
Views: 150
Reputation: 12206
You can do this:
$local = [
'www.example.devlocal'
];
if (!in_array($_SERVER['SERVER_NAME'], $local)) {
// Development server
} else {
//Local server
}
Or you can also detect by IP address of the server:
$whitelist = array(
'127.0.0.1',
'::1'
);
if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
// This is production server
}
Upvotes: 1
Reputation: 38308
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
}
Upvotes: 4
Reputation: 40861
A good way is to only store the database credentials in the specific environment on which they are supposed to be used.
So you could create a db.credentials.php
file on both the local and remote servers. The contents of which would be respectively different, but something like this:
<?php
$databasename = "myDB";
$username = "me";
$password = "C0mpl3x P@55w0rd";
Then you simply source that file in your php code:
require_once("path/to/db.credentials.php");
Upvotes: 1
Reputation: 40861
you can check the server name to see if it's local host with something like:
if($_SERVER['SERVER_NAME'] == "localhost")
$database_credentials = "local";
else
$database_credentials = "remote";
Upvotes: 0