Best way to connect to MySQL with PHP securely [du

2019-01-10 09:53发布

This question already has an answer here:

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?

5条回答
beautiful°
2楼-- · 2019-01-10 10:36
  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.
查看更多
干净又极端
3楼-- · 2019-01-10 10:47

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.

查看更多
做个烂人
4楼-- · 2019-01-10 10:49

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.

查看更多
\"骚年 ilove
5楼-- · 2019-01-10 10:50

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

查看更多
趁早两清
6楼-- · 2019-01-10 10:51
  • 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")

查看更多
登录 后发表回答