当PHP应用程序建立数据库连接时,当然通常需要传递登录名和密码。如果我对我的应用程序使用一个最小权限的登录,那么PHP需要知道这个登录名和密码。保护密码的最好方法是什么?只在PHP代码中编写它似乎不是一个好主意。


当前回答

最安全的方法是在PHP代码中完全不指定这些信息。

如果你使用Apache,这意味着在httpd.conf或虚拟主机文件中设置连接细节。如果你这样做,你可以不带参数地调用mysql_connect(),这意味着PHP永远不会输出你的信息。

这是你在这些文件中指定这些值的方法:

php_value mysql.default.user      myusername
php_value mysql.default.password  mypassword
php_value mysql.default.host      server

然后像这样打开mysql连接:

<?php
$db = mysqli_connect();

或者像这样:

<?php
$db = mysqli_connect(ini_get("mysql.default.user"),
                     ini_get("mysql.default.password"),
                     ini_get("mysql.default.host"));

其他回答

最安全的方法是在PHP代码中完全不指定这些信息。

如果你使用Apache,这意味着在httpd.conf或虚拟主机文件中设置连接细节。如果你这样做,你可以不带参数地调用mysql_connect(),这意味着PHP永远不会输出你的信息。

这是你在这些文件中指定这些值的方法:

php_value mysql.default.user      myusername
php_value mysql.default.password  mypassword
php_value mysql.default.host      server

然后像这样打开mysql连接:

<?php
$db = mysqli_connect();

或者像这样:

<?php
$db = mysqli_connect(ini_get("mysql.default.user"),
                     ini_get("mysql.default.password"),
                     ini_get("mysql.default.host"));

我们是这样解决的:

Use memcache on server, with open connection from other password server. Save to memcache the password (or even all the password.php file encrypted) plus the decrypt key. The web site, calls the memcache key holding the password file passphrase and decrypt in memory all the passwords. The password server send a new encrypted password file every 5 minutes. If you using encrypted password.php on your project, you put an audit, that check if this file was touched externally - or viewed. When this happens, you automatically can clean the memory, as well as close the server for access.

是否可以在存储凭据的同一文件中创建数据库连接。将凭据内联到connect语句中。

mysql_connect("localhost", "me", "mypass");

否则最好在connect语句之后取消设置凭据,因为不在内存中的凭据不能从内存中读取;)

include("/outside-webroot/db_settings.php");  
mysql_connect("localhost", $db_user, $db_pass);  
unset ($db_user, $db_pass);  

将它们存储在web根目录外的一个文件中。

只是把它放在配置文件的某个地方是通常完成的方式。只要确保你:

禁止从网络外的任何服务器访问数据库, 注意不要意外地向用户显示密码(在错误消息中,或通过PHP文件意外地作为HTML提供,等等)。