简体   繁体   English

在PHP应用程序中确保数据库凭据的安全

[英]Keeping database credentials secure in a PHP application

I'm working on my first PHP application. 我正在开发我的第一个PHP应用程序。 Right now, I'm keeping my database connection details in constants in a config file outside of my root folder, as I read this is the most secure way to prevent people from getting your database credentials. 现在,我将数据库连接详细信息保持在根文件夹之外的配置文件中的常量中,因为我读到这是防止人们获取您的数据库凭据的最安全的方法。

If I include that file into my PHP application, aren't those constants now visible everywhere in my code and isn't that still a bad thing? 如果我将该文件包含到我的PHP应用程序中,这些常量现在在我的代码中到处都可见吗,那还不是一件坏事吗? My personal idea to overcome this is just to create a database class, also store it outside of the root directory, and then put my credentials in private parameters. 解决这个问题的我个人想法只是创建一个数据库类,还将其存储在根目录之外,然后将我的凭据放入私有参数中。 So it would be something like this: 所以会是这样的:

class Db {

    private $host = 'host';
    private $dbname = 'dbname';
    private $username = 'username';
    private $password = 'password';

    private $connection;

    public function __construct() {
        $this->open_connection();
    }

    private function open_connection() {
        try {
            $this->connection = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->username, $this->password);
        } catch (PDOException $ex) {
            // handle exception
        }
    }

}

And then I would just include this file instead, any thoughts? 然后,我将包括这个文件,有什么想法吗?

If someone gets access to your PHP source files, you have bigger problems than your database login being found. 如果有人可以访问您的PHP源文件,那么您遇到的问题比找到数据库登录名还要大。 Just saying. 只是说。

I keep my DB credentials in a place that makes sense: in the function call that connects to the database. 我将数据库凭据保存在有意义的位置:在连接到数据库的函数调用中。

That would add some security, but I'm not sure it'd be completely worth it. 那会增加一些安全性,但是我不确定这是否完全值得。 The reason you keep the config file outside of the root directory is to prevent clients from calling up the credentials on the web. 您将配置文件保留在根目录之外的原因是为了防止客户端调用Web上的凭据。 It should be safe with your first method as long as the user has no way to execute their own PHP, which they shouldn't. 只要用户无法执行自己的PHP,而您不应该执行,则第一种方法应该是安全的。

You should be more focused on making it more difficult if they have terminal access. 如果他们拥有终端访问权限,则应更加专注于使其更加困难。 You should lock down the files so only root can see them. 您应该锁定文件,以便只有root才能看到它们。 Also disable outside DB access, block port 3306 in the firewall and disable Mysql networking. 还禁用外部数据库访问,在防火墙中阻止端口3306,并禁用Mysql网络。 Use this. 用这个。 I hope this helps, and good luck. 我希望这个帮助能祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM