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


当前回答

如果谈论的是数据库密码,而不是来自浏览器的密码,标准的做法似乎是将数据库密码放在服务器上的PHP配置文件中。

您只需要确保包含密码的php文件具有适当的权限即可。也就是说,它应该是可读的只有web服务器和您的用户帐户。

其他回答

如果谈论的是数据库密码,而不是来自浏览器的密码,标准的做法似乎是将数据库密码放在服务器上的PHP配置文件中。

您只需要确保包含密码的php文件具有适当的权限即可。也就是说,它应该是可读的只有web服务器和您的用户帐户。

如果你正在使用PostgreSQL,那么它在~/。Pgpass自动设置密码。有关更多信息,请参阅手册。

之前我们将DB user/pass存储在一个配置文件中,但后来进入了偏执模式——采用了深度防御策略。

如果您的应用程序被泄露,用户将拥有对您的配置文件的读访问权,因此黑客就有可能读取这些信息。配置文件也可能在版本控制中被捕获,或者在服务器中被复制。

我们已经切换到在Apache VirtualHost中设置的环境变量中存储user/pass。这个配置只能由根用户读取——希望您的Apache用户不是以根用户身份运行。

这样做的缺点是,现在密码在一个全局PHP变量中。

为了降低这种风险,我们有以下预防措施:

The password is encrypted. We extend the PDO class to include logic for decrypting the password. If someone reads the code where we establish a connection, it won't be obvious that the connection is being established with an encrypted password and not the password itself. The encrypted password is moved from the global variables into a private variable The application does this immediately to reduce the window that the value is available in the global space. phpinfo() is disabled. PHPInfo is an easy target to get an overview of everything, including environment variables.

是否可以在存储凭据的同一文件中创建数据库连接。将凭据内联到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);  

实际上,最好的做法是将数据库凭据存储在环境变量中,因为:

These credentials are dependant to environment, it means that you won't have the same credentials in dev/prod. Storing them in the same file for all environment is a mistake. Credentials are not related to business logic which means login and password have nothing to do in your code. You can set environment variables without creating any business code class file, which means you will never make the mistake of adding the credential files to a commit in Git. Environments variables are superglobales : you can use them everywhere in your code without including any file.

如何使用它们?

使用$_ENV数组: 设置:$_ENV['MYVAR'] = $ MYVAR 获取:echo $_ENV["MYVAR"] 使用php函数: 设置与putenv函数- putenv("MYVAR=$ MYVAR "); 使用getenv函数获取- getenv('MYVAR'); 在vhosts文件和.htaccess中,但不建议这样做,因为它在另一个文件中,这样做并不能解决问题。

您可以轻松地删除包含所有环境变量的文件(如envars .php)并执行它(php envars .php)并删除它。这有点老派,但它仍然可以工作,而且服务器中没有任何带有凭据的文件,代码中也没有凭据。由于这有点费力,框架做得更好。

Symfony的例子(不只是PHP) 像Symfony这样的现代框架建议使用环境变量,并将它们存储在.env未提交的文件中或直接存储在命令行中,这意味着你可以这样做:

使用CLI: symfony var:set FOO=bar——env-level 用。env或。env。local: FOO="bar"

文档: