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


当前回答

我们是这样解决的:

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.

其他回答

最安全的方法是在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配置文件中。

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

有些人把这个问题误解为如何在数据库中存储密码。这是错误的。它是关于如何存储密码,让您进入数据库。

通常的解决方案是将密码从源代码移到配置文件中。然后,将管理和保护配置文件的工作交给系统管理员。这样,开发人员就不需要知道任何关于产品密码的信息,并且在源代码控制中也没有密码记录。

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

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"

文档:

将数据库密码放在一个文件中,使其对提供文件的用户只读。

除非您有某种方法只允许php服务器进程访问数据库,否则这几乎就是您所能做的全部工作。