Image courtesy of ddpavumba at FreeDigitalPhotos.net

It is recommended that 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 ]] )

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 = superuser
password = rDP0Vm1fyIggpVfHpPez

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;

	}
} 
?>

 

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.