I am developing a website that will eventually be connecting to a mySQL database. My question is how do I safely and securely store those credentials to access that database within my PHP site without risk of them accidentally being compromised by, for example, the server returning PHP as normal text? Any help is appreciated, thanks! :)
While storing password place holders in config files is a good start; creating a data source and connection pool programmatically will ensure that the database credentials are not stored on the build server (after parameter replacement in code) or on on the drive on the production server and are thus impervious to theft.
There is an additional risk with storing passwords in a .php file within your webroot, which is a bit obscure but can be easily avoided by placing the file outside of your web root.
My connection.php file stores the credentials to connect to the database: When a page need to connect the database I just use <?php include ("connection.php"); ?>.
The idea is to use a properties file or framework-specific configuration file to store credentials and then use it in code at run time. While it is extremely easy to get going; the credentials will make their way into the version control system and thus extremely vulnerable to theft and misuse. Zero implementation time.
Common practices for this problem include putting the database credentials in a configuration file that is not PHP, such as a .ini file, and then reading that with PHP. To add extra security you should also put the configuration file outside of the web root, so that you can be sure no one can access the file by navigating directly to it.
For example, the Laravel framework (among others) define the web root in the /public directory, while outside that directory is a .env
file containing database credentials among other settings.
Have a look here for more info: How to secure database passwords in PHP?
More importantly though, you should never have to worry about your PHP being served as plain text. Take the proper development precautions to ensure this never happens. Some starting points are:
.php
and not .html
(unless you use this work around)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With