Best way to connect to MySQL with PHP securely [du

2019-01-10 10:12发布

问题:

This question already has an answer here:

  • How to secure database passwords in PHP? 17 answers

I want some input on what you guys think is the most secure way to connect to a MySQL database using PHP. Currently the way I'm doing it is a utility PHP file that I include in the top of all my other PHP files. The utility PHP file is this:

<?php
    if(!defined('IN_PHP')){
        die("hackerssss");
    }
    $mysql_host = "localhost";
    $mysql_user = "root";
    $mysql_pass = "root";
    $mysql_db = cokertrading;
?>

Any suggestions?

回答1:

Suggestion: You should probably never be running as root; create another account and give it the 'least' privileges required for your site.



回答2:

I can believe noone has mentioned MYSQLI and prepared statements yet, you may lock your password and database connection away, but thats ultimately futile if I can simply type ';DROP TABLE users;-- in the login form.

Check http://en.wikipedia.org/wiki/SQL_injection for an idea about what I'm talking about.



回答3:

  • Define a pair of proper login credentials instead of "root/root" (change the user name to something else, and choose a complicated password);

  • if possible restrict access to the database to localhost on a firewall level or, as @Scott says in the comments, set mySQL to listen to connections from 127.0.0.1 only. If both is not possible, restrict access on mySQL level. ("username"@"localhost")



回答4:

  1. Remember that anyone who can read that file will know your SQL password: set it not readable by others.
  2. Don't login with root: create a user for each application.
  3. Don't use "root" as your root password.
  4. Don't give your password to everyone.


回答5:

Because PHP scripts are server side - i.e. they are parsed on the server and only the output is sent to the browser - the way you are doing this is perfectly secure.

The only way that people would be able to get your username and password would be to actually hack into your server and view the source code - in which case there's no way (in PHP) to protect against this.