简体   繁体   中英

While connecting to a MySql database with PHP, is it a bad idea to modify the db config based on user input?

Sorry if the title is not clear, I'm in a project where we're building an Android app that connects to a MySql database to display some data. We're using PHP to connect to the database, and we're using dbconfig.php that contains something along the lines of:

define("servername", "host");
define("username", "username");
define("password", "password");
define("database",  "database");

Since we are often connecting to databases hosted in different servers, we had to manually change the dbconfig every time before running the app, so we're thinking of letting the user write this information on the app itself. I thought of making the app send a POST request then having the dbconfig have something like this:

define("servername", $_POST["host"]);
define("username", $_POST["username"]);
define("password", $_POST["password"]);
define("database",  $_POST["database"]);

But I know the dbconfig is supposed to be secure so I am not comfortable dynamically changing the dbconfig and looks like a bad idea. What is the best way of achieving this?

Edit: It is a bad idea, on another note how would an app similar to this work? Would it not require some type of POST request to send the database credentials onto a server side language?

This is a real bad idea, because:

  • you are passing credentials via POST
  • you do not sanitize/strip the credentials (the $_POST content)
  • you are transferring your credentials via HTTP(S) (or something else)

One approach is to define some REST endpoints and let your app call those endpoints. The endpoints can then decide to which server they are going to connect.

if you are in development mode you could have a different home page to send the name of the database to use .. something similar to this

$db = isset($_POST['db']) ? $_POST['db'] : 'default';

switch ($db) {
    case 'db1':
        $servername = 'host1';
        $username   = 'username1';
        $password   = 'password1';
        $database   = 'database1';
        break;
    case 'db2':
        $servername = 'host2';
        $username   = 'username2';
        $password   = 'password2';
        $database   = 'database2';
        break;
    default:
        $servername = 'default_host';
        $username   = 'default_username';
        $password   = 'default_password';
        $database   = 'default_database';
        break;
}

define("SERVERNAME", $servername);
define("USERNAME",   $username);
define("PASSWORD",   $password);
define("DATABASE",   $database);

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