Nate Loder Nate Loder - 10 months ago 21
PHP Question

Automatically define username and password for mysqli depending on server type. Good idea?

I've created a page to include with all my connections that will automatically set my sql username and password, as well as error reporting settings, depending on whether the connection is being made with the testing server or the live site. Wondering if this is a good idea? Why or why not? Am I just being lazy or is there a better way of doing this?

# This will set username and password for database access, as well as error reporting according to the server being used.

# It eliminates the need to change code when switching from testing environment to live site.

# Let's find out which server is being used and take the first 3 characters of the server name.

$thisServer = substr($_SERVER['SERVER_NAME'], 0, 3);

# If on localhost (testing server):
if($thisServer == 'loc'){

# enable php error reporting

# enable mysqli reporting
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

# set username and password
$dbHost = '';
$dbUserName = 'myUser';
$dbPassword = 'myPassword';

# If on remote server:
} elseif($thisServer == 'www') { # <-- This should be first 3 characters you see in URL of live site.

# disable php error reporting

# disable mysqli reporting
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_OFF;

# set username and password
$dbHost = '';
$dbUserName = 'myUser';
$dbPassword = 'myPassword';


I'm assuming you're using Apache, I expect Nginx could handle similar functionality. You presumably have different virtual hosts on your web server for production and development environments. You can have the web server set the desired variables for you:

<VirtualHost *:80>
    SetEnv DB_HOST    "localhost"
    SetEnv DB_USER    "myUser"
    SetEnv DB_PASS    "myPassword"
    SetEnv DB_REPORT  "0"
    SetEnv ERR_REPORTING "0"

<VirtualHost *:80>
    ServerName localhost
    SetEnv DB_HOST    "localhost"
    SetEnv DB_USER    "testUser"
    SetEnv DB_PASS    "testPassword"
    SetEnv DB_REPORT  "255"
    SetEnv ERR_REPORTING "-1"

Then, in your PHP code you can retrieve them. Same code for both servers, nice and neat.

$dbHost = getenv("DB_HOST");
$dbUserName = getenv("DB_USER");
$dbPassword = getenv("DB_PASS");
$dbReporting = (int)getenv("DB_REPORT");
$errLevel = (int)getenv("ERR_REPORTING");

$driver = new mysqli_driver();
$driver->report_mode = $dbReporting;

Another advantage of this approach is the isolation of database credentials from people who don't need them.