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


当前回答

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

其他回答

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

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

你的选择是有限的,因为你说你需要密码来访问数据库。一种常用的方法是将用户名和密码存储在单独的配置文件中,而不是主脚本中。然后确保将其存储在主web树之外。这是如果有一个web配置问题,让你的php文件只是显示为文本,而不是执行,你还没有暴露密码。

除此之外,你是在正确的行与最小的访问所使用的帐户。再加上

不要使用用户名/密码的组合 将数据库服务器配置为只接受来自该用户的web主机的连接(如果DB在同一台机器上,localhost更好),这样即使凭证暴露出来,它们对任何人都没有用处,除非他们有其他访问机器的权限。 混淆密码(即使是ROT13也可以),如果有人访问了文件,它不会提供太多的防御,但至少可以防止随意查看它。

彼得

我们是这样解决的:

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.

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

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单独的配置文件,如下所示:

<?php exit() ?>

[...]

Plain text data including password

这并不妨碍您正确地设置访问规则。但如果你的网站被黑客攻击,“要求”或“包括”将在第一行退出脚本,因此更难获得数据。

然而,不要让配置文件在可以通过web访问的目录中。你应该有一个“Web”文件夹,包含你的控制器代码,css,图片和js。这是所有。其他的都放在脱机文件夹中。