Blog

The caffeine fuelled writings of a web developer


local-dev-workflow

Dynamic credentials for local and live environments in PHP

Posted on May 18th 2016  //  Filed under: Web Development

I love when I find a way to improve my workflow. I recently started using an SFTP/FTP plugin for Sublime Text 3 which is really great for mapping my local folder to a remote folder on my live development server.

However, I found myself getting annoyed that every time I committed my folder I had to go into my config file and change the PHP code to return the live, more secure database credentials.

The code

The PHP block below simply identifies if the the host is localhost or server based on your local environment and provides a standard root login, localhost set of results. If not, it will provide the secure credentials for the server.

if($_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "server") {
	define('DBUSER', 'root');
	define('DBPASS', '');
	define('DBSERVER', 'localhost');
	define('DBNAME', 'web');
}
else {
	define('DBUSER', 'secure_user');
	define('DBPASS', '*********');
	define('DBSERVER', 'host.secure.secret.net');
	define('DBNAME', 'web');
}

Why is this necessary?

There are a variety of reasons I like this approach. It is never a good idea to login into a live database as root. I can also define the correct host information for a live environment without having to edit the file *

* This is the key field I need to change as my live environment does not allow localhost login for security.

Tidying up

When you have built your epic software, I would recommend you remove this code. It just tidies your PHP code up in the configuration and is one less condition to process.

Get in touch

Please get in touch via email or twitter if you’d like to discuss!