Import Login Information for Database Connection Scripts

I'm starting to realize that importing the script used to establish a database connections isn't enough. Being able to import a script wherever the database is needed does simplify the process of changing a database password since it only needs to be changed in one place. However, I keep finding reasons to make major revisions to the connection script which usually results in having multiple versions and I don't always have the time to complete the upgrade process. All of those connection scripts need to be updated when the password changes.

Background

Now, of course, I would rather change two or three database connection scripts over hundreds or thousands of individual pages. But it would be nice to get back to changing the password in a single place.

To show how this can be accomplished, we'll use the database connection script from the post titled "End PHP Scripts Gracefully After a Failed Database Connection".

<?php
class connect {
     //DECLARE PROPERTIES
     public $success        = false;
     public $errorText      = '';
     public $databaseObject = '';
 
     //CONSTRUCTOR
     public function __construct($endProgram=false) {
          //INITIALIZE PROPERTIES
          $host     = 'yourhostname.com';
          $database = 'your_database_name';
          $username = 'your_username';
          $password = 'your_password';
 
          //IF THE DATABASE CONNECTION FAILS, FLAG ERROR
          $mysqli = new mysqli($host, $username, $password, $database);
          if($mysqli->connect_errno) {
               $this->errorText = 'There was a problem connecting to the database that this portion of the website requires to display properly.';
          } else {
               $this->databaseObject = $mysqli;
               $this->success        = true;
          }
 
          //IF A PAGE DOESN'T FUNCTION WITHOUT THE DATABASE --AND-- THE CONNECTION FAILED, DISPLAY THE ERROR AND STOP THE SCRIPT
          if($endProgram && !$this->success) {
               print $this->errorText;
               exit;
          }
     }
}
?>

Solution

First, we'll create a new PHP file named "database_credentials.php" which holds the class for getting the login credentials.

<?php
class databaseInfo {
    //...
}
?>

The database username and password is then added to a class property. Note that the static keyword is used since the databaseInfo class doesn't need to persist throughout the entire database connection script. It's just used to quickly get the database login information.

<?php
class databaseInfo {
    //INITIALIZE PROPERTIES
    private static $main = array(
        'user' => 'your_username',
        'pass' => 'your_password'
    );

}
?>

Since the username and password are hidden behind a private class property, the class needs a method for accessing the login information. Note that the method will also be static.

<?php
class databaseInfo {
    //INITIALIZE PROPERTIES
    private static $main = array(
        'user' => 'your_username',
        'pass' => 'your_password'
    );
 
    //METHOD RETURNS THE REQUESTED LOGIN CREDENTIALS
    public static function getLogin($type) {
        if(in_array($type, array('main'))) {
            return self::$$type;
        }
    }

}
?>

Final Code — Database Credentials Script

To help give you a better sense on how the pieces fit together, the entire script can be found below.

<?php
class databaseInfo {
    //INITIALIZE PROPERTIES
    private static $main = array(
        'user' => 'your_username',
        'pass' => 'your_password'
    );
 
    //METHOD RETURNS THE REQUESTED LOGIN CREDENTIALS
    public static function getLogin($type) {
        if(in_array($type, array('main'))) {
            return self::$$type;
        }
    }
}
?>

Final Code — Database Connection Script

Note that the database credentials script (database_credentials.php) should be uploaded to a folder that is outside of your website's root folder. Otherwise your login information could be compromised if your server is ever misconfigured.

Assuming the script was uploaded just outside of the website root, you could modify the database connection script as follows:

<?php
class connect {
     //DECLARE PROPERTIES
     public $success        = false;
     public $errorText      = '';
     public $databaseObject = '';
 
     //CONSTRUCTOR
     public function __construct($endProgram=false) {
          //GET LOGIN CREDENTIALS
          require_once "{$_SERVER['DOCUMENT_ROOT']}/../database_credentials.php";
          $credentials = databaseInfo::getLogin('main');

 
          //INITIALIZE PROPERTIES
          $host     = 'yourhostname.com';
          $database = 'your_database_name';
          $username = $credentials['user'];
          $password = $credentials['pass'];

 
          //IF THE DATABASE CONNECTION FAILS, FLAG ERROR
          $mysqli = new mysqli($host, $username, $password, $database);
          if($mysqli->connect_errno) {
               $this->errorText = 'There was a problem connecting to the database that this portion of the website requires to display properly.';
          } else {
               $this->databaseObject = $mysqli;
               $this->success        = true;
          }
 
          //IF A PAGE DOESN'T FUNCTION WITHOUT THE DATABASE --AND-- THE CONNECTION FAILED, DISPLAY THE ERROR AND STOP THE SCRIPT
          if($endProgram && !$this->success) {
               print $this->errorText;
               exit;
          }
     }
}
?>

Final Thoughts

In addition to only needing to update the password in one place, the new connection script can easily be modified to support multiple database logins. You would just need to create another property in the databaseInfo class with the alternate login information. And then pass the property name through the call to the getLogin() method.

Related Posts

0 Comments

There are currently no comments.

Leave a Comment