Question

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"
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top