Add Environment variables to CakePHP

 Mar 19, 2013

It should be common knowledge that you never put sensitive information into source control, but recently its been shown that many developers leave paswords, usernames even private SSH keys in their repositories (even public ones)

A great way to manage sensitive values in a web application, such as passwords to web services, databases etc, is to store them in the environment and access them from the code.

<?php
// contrived example!
$connection = open_con(getenv('DB_USER'), getenv('DB_PASS'));

These environment variables can then be setup on the server via apache, nginx, or other means to ensure they are available to the code, but not actually in the code.

It also means you don’t have to change and re-deploy your code if you need to change a password for some reason.

However, what does this mean for developing locally? You can’t always store environment variables in your local machine, or may not want to. Especially if you develop lots of apps with different variables, it could become a maintenance nightmare… and what happens when you upgrade or change your computer?

Here is one suggestion for working with CakePHP although it could be applied to any PHP project.

Add the following code to your Config/bootstrap.php so that it loads each time the app runs.

I prefer JSON as a format myself, but you may want to change it to something else.

<?php
# in Config/bootstrap.php

// import any environment variables from the .env file (if it exists)
if(is_file(APP . DS . '.env')) {
  $vars = json_decode(file_get_contents(APP . DS . '.env'), true);
  foreach ($vars as $name => $val) {
    putenv("$name=$val");
  }
}

Then in the app directory add a .env file and simply add each environment variable to it

{
"DB_USER" : "user_name",
"DB_PASS" : "password"
}

Then just append this file to your .gitignore file to prevent it ending up in source control and you’re done.

You could even have a .env setup for the production server which is copied to the apo directory during a deploy and allow this method to handle the environment variables on the server too.

For Ruby there are gems out there that do similar, or you could look into Foreman, which has similar functions too but this is a nice simple solution if you don’t want to run other tools along side your CakePHP development.