6

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! :)

scarecrow850
  • 173
  • 2
  • 11

1 Answers1

6

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:

  • Making sure you have PHP installed!
  • Make sure you open and close your tags properly
  • Make sure your file extension is .php and not .html (unless you use this work around)
  • Also make sure in production code that you aren't displaying errors on the page (display_errors ini)
Community
  • 1
  • 1
samrap
  • 5,245
  • 5
  • 29
  • 55
  • how do you take the proper development precautions as you say. Help the OP to understand that. Just make it part of your answer – Drew Sep 11 '15 at 00:22
  • Do hosting services generally allow a folder outside of the web root on shared plans? Sorry if that's kinda out of the scope of the question, but I don't have a lot of experience with hosting plans. thank you for the answer by the way! – scarecrow850 Sep 11 '15 at 00:24
  • @scarecrow850 I am not sure. I always use VPS but if you are using a service like godaddy or ipage then it is not likely. In that case, take a look at using .htaccess to block certain files from being viewed – samrap Sep 11 '15 at 00:29
  • I'm planning on using HostGator for my hosting, but I can only do the basic hosting plan, is there any risk of the .htaccess method failing and not blocking it? – scarecrow850 Sep 11 '15 at 00:31
  • Unless the file is renamed or the htaccess edited then no you will be safe – samrap Sep 11 '15 at 00:32
  • 1
    Thanks for your help, I appreciate it! :) – scarecrow850 Sep 11 '15 at 00:35
  • you're welcome, if you would like to accept this answer, click the star next to it, and welcome to stack overflow! – samrap Sep 11 '15 at 00:36