简体   繁体   中英

Keeping database credentials secure in a PHP application

I'm working on my first PHP application. 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? 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. 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. 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.

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. Also disable outside DB access, block port 3306 in the firewall and disable Mysql networking. Use this. I hope this helps, and good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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