I'm writing one custom class for PDO connection.
I want these advantages:
- Protect credentials: user, password ...
- Facilitate maintenance: facing future password changes for example
- Facilitate connection:
$pdo=new MyPDO();
- Provide my class with all the PDO functionalities
I write my class as you can see here:
For protecting credentials I saved them into an ini
file:
<?php return; ?>
; credentials
host=localhost
user=myUser
pass="my/very/secure/password.../UqMsN[)VPn&gunmv3KzE?3Q&Qw/..."
dbname=myDataBase
The class
class MyPDO extends PDO
{
public function __construct()
{
$iniData = parse_ini_file("//home/.credentials/db.php.ini");
$host=$iniData["host"];
$dbname=$iniData["dbname"];
$user=$iniData["user"];
$pass=$iniData["pass"];
$dsn = "mysql:host=$host;dbname=$dbname";
$options = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
);
try {
parent::__construct($dsn, $user, $pass, $options);
} catch (PDOException $e) {
error_log($this->error = $e->getMessage(),0);
}
}
}
?>
Usage example
include_once('MyPDO.php');
$pdo=new MyPDO();
/*Use any PDO method*/
$pdo->query(...);
$pdo->prepare(...);
$pdo->execute(...);
public_html
, then, non navigation possible (i'm using shared hosting). 2º. The first line:<?php return; ?>
prevents to show the file content in case of access to fila via browser. I think the info is protected so. \$\endgroup\$