在 php.ini 中存储 PDO 详细信息
根据PDO文档,您可以在php中存储数据库登录详细信息.ini,远离 php 文件(示例 3)。但它没有解释如何存储用户名和密码,只解释了数据库和主机。你会怎么做?
这是文档中使用的方法:
[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"
我尝试将用户名和密码添加到主机,但它不喜欢用户名和密码之间的 : ,并且它无法将仅包含用户名的地址识别为真实地址:
[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=username:password@localhost"
我还尝试将用户名和密码作为单独的参数,但事实并非如此。
[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"
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据文档,这是不可能的。并且可能不想要。如果你看一下 PDO __construct() 方法,它需要 3 个参数:一个 DSN(可以是 php.ini 中定义的
pdo.dsn.name
的名称)。 ini)、用户名和密码。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 apdo.dsn.name
defined in your php.ini), a username and a password.您可以将数据库用户名和密码存储在环境变量中,然后可以在 PHP 脚本的
$_ENV
超全局变量中使用该环境变量。AFIACT,您无法从 php.ini 设置环境变量,但您可以在 apache 配置中设置它,包括在 .htaccess 文件中。例如,
然后在 PHP 中您可以使用:
您还可以将 DSN 作为环境变量以将其全部放在一起。
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.
Then in your PHP you can use:
You could also put the DSN as an environment variable to keep it all together.