MySQL, PHP & HTML5 banner

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.


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

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

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

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/>";

public function authenticate($user, $pass) {
    $sql = "SELECT * FROM `users` WHERE `userName` = :user_name AND `userPass` = :user_pass LIMIT 1;";
    $stmt = $this->connection->prepare($sql);
        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 served 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.

By foxbeefly

PHP / MySQL Developer. HTML, CSS and some JavaScript.

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.