Image courtesy of ddpavumba at FreeDigitalPhotos.net

It is recommended that for security reasons you do not include database connection details in your scripts, so where exactly do you store them? Luckily, PHP has the handy function parse_ini_file() specifically for this task.

From php.net:

parse_ini_file ( string $filename [, bool $process_sections = FALSE [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) : array

The $process_sections parameter allows you to set section headings which then results in an associative array being returned.

Simply create an ini file — I called mine db.ini

[database]
driver = mysql
host = localhost;
port = 3306
schema = databasename
username = kingofrocknroll
password = supersecretrandomsiedpassword

Then, in your code — I am using it in my Auth class:

<?php
class Auth {
    public static $dns = null;
    public $connection;

    function __construct($file = 'db.ini') {
        if (!$settings = parse_ini_file($file, TRUE)) {
            throw new Exception('Unable to open ' . $file);
        }
        $this->dns = $settings['database']['driver']. ':host=' . $settings['database']['host']. ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : ''). ';dbname=' . $settings['database']['schema'];
    try {
            $this->connection = new PDO($this->dns, $settings['database']['username'], $settings['database']['password']);
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
    }
}

public function authenticate($user, $pass) {
    $sql = "SELECT * FROM `users` WHERE `userName` = :user_name AND `userPass` = :user_pass LIMIT 1;";
    $stmt = $this->connection->prepare($sql);
    $stmt->execute(
        array( ':user_name' => $user, ':user_pass' => $pass ) );
        $details = $stmt->fetchAll(); 
        if($stmt->rowCount()>0) {
            return true;
        }
        return false;
    }
}
?>

The .ini file gets parsed by the server as a plain text file so you must ensure that your .ini files cannot be server up.

ini files are generally treated as plain text by web servers and thus served to browsers if requested. That means for security you must either keep your ini files outside of your docroot or reconfigure your web server to not serve them. Failure to do either of those may introduce a security risk.

https://www.php.net/manual/en/function.parse-ini-file.php

By foxbeefly

PHP / MySQL Developer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.