设置不带密码的PDO连接 [英] Set up PDO connection without password

查看:166
本文介绍了设置不带密码的PDO连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到数据库,但是出于安全考虑,我更改了数据库的root密码.但是,为了连接到数据库并使用PDO,我显然必须在php中传递密码,这显然不利于安全性:

I'm trying to connect to my database, but I changed my database's root password in the interest of security. However, in order to connect to the database and use PDO, I apparently have to pass my password in the php, which obviously is not good for security:

$hsdbc = new PDO('mysql:dbname=hs database;host=127.0.0.1;charset=utf8', 'root','passwordgoeshere');

$hsdbc->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$hsdbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

我很愚蠢,那是因为它不是PHP,但是查看实际文件的人将能够看到密码,或者有某种方法可以在不将密码传递到文件中的情况下完成密码.

Am I being stupid and that because it's PHP no-one but the person who views the actual file will be able to see the password, or is there some way to do it without passing the password in the file.

推荐答案

当PHP的Apache类型处理程序被意外取消配置时,我看到了暴露PHP代码的网站.然后,将显示.php文件中的代码,而不是执行它们.还有一个Apache类型处理程序可以故意显示PHP源代码,尽管通常不进行配置.

I have seen websites that expose PHP code, when the Apache type handler for PHP becomes unconfigured by accident. Then the code in .php files is displayed instead of executed. There's also an Apache type handler to display PHP source deliberately, though this is not usually configured.

为避免此漏洞,建议您将敏感的PHP代码放在htdocs目录之外.而是在您的htdocs目录中放置一个最小的PHP脚本,该脚本使用include()require()加载其余代码.

To avoid this vulnerability, it's a good practice to put your sensitive PHP code outside your htdocs directory. Instead, put in your htdocs directory a minimal PHP script that loads the rest of the code using include() or require().

另一种选择是将MySQL凭据放在配置文件中,而不是放在PHP代码中.例如,PHP函数 parse_ini_file().这样可以很容易地将MySQL密码存储在代码之外.

An alternative is to put your MySQL credentials in a config file instead of PHP code at all. For example, the file format used by /etc/my.cnf and $HOME/.my.cnf is readable by the PHP function parse_ini_file(). It's easy to store your MySQL password outside of your code this way.

例如,从/etc/my.cnf的[mysql][client]部分中读取 user password :

For example, read user and password from the [mysql] or [client] sections of /etc/my.cnf:

$ini = parse_ini_file("/etc/my.cnf", true);

if (array_key_exists("mysql", $ini)) {
    $connect_opts = array_merge($connect_opts, $ini["mysql"]);
} else if (array_key_exists("client", $ini)) {
    $connect_opts = array_merge($connect_opts, $ini["client"]);
}

$pdo = new PDO($dsn, $connect_opts["user"], $connect_opts["password"]);

这篇关于设置不带密码的PDO连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆