tags:

views:

164

answers:

2

According to the PDO documentation, you can store database login details in php.ini, away from the php file (example 3). But it does not explain how to store username and password, only the database and host. How would you do that?

This is the method used in the documentation:

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"

I've tried adding the username and password to the host, but it does not like : between the username and password, and it does not recognize an address with only a username as a real address:

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=username:password@localhost"

I've also tried putting the username and password as separate arguments, but it does not.s

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost;username:username;password:secret"
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost;uid:username;pwd:secret"
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost;UID:username;PWD:secret"
+1  A: 

According to the documentation, this is not possible. And probably not wanted. If you look at the PDO __construct() method, it takes 3 arguments: a DSN (which can be a name to a pdo.dsn.name defined in your php.ini), a username and a password.

JP
Actually, this is not entirely true - it's all up to the PDO driver. For example, in pgsql, defining the user and pass in the DSN work just fine (you can pass an empty string as the other two parameters). From the docs at http://php.net/pdo-pgsql.connection: user The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor. password The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.
TML
A: 

You can store the DB username and password in an environment variable, which is then available inside the PHP script in the $_ENV superglobal.

AFIACT, you can't set an environment variable from php.ini, but you can set it the apache config, including in a .htaccess file. E.g.

SetEnv mysql_username dbuser
SetEnv mysql_password dbpass

Then in your PHP you can use:

$db = new PDO('mydb',$_ENV['mysql_username'],$_ENV['mysql_password']);

You could also put the DSN as an environment variable to keep it all together.

rjmunro