I have a dbconfig.php
file which contains the MySQL database name, host, username and password to connect to the database.
// dbconfig.php
$host = '127.0.0.1';
$username = 'root';
$password = '';
$db_name = 'mydb';
$db = new PDO('mysql:host='.$host.';dbname='.$db_name.';charset=utf8', $username , $password);
I have a HTML form which allows you to set from the UI the database credentials, so the strings above come from user input and are saved directly into this file by writing them when the form is submitted.
How can I sanitize the strings so that it can't be exploited? Currently I write the strings like this:
function sanitizeStr($string) {
$string = str_replace("\\", "\\\\", $string);
return var_export($string, true);
}
$pattern = "/\\\$host = .*;/";
$newpat = '\$host = ' . sanitizeStr($_POST['db_host']) . ';';
$contents = preg_replace($pattern, $newpat, $contents);
// ... same for $username, $password and $db_name
Are str_replace
and var_export
enough to stop code from being injected into dbconfig.php
?
I can not try a really aggresive sanitization (such as allowing only specific characters) because this would force the user to have a MySQL password which only contans those characters.
How can I make sure that the string from the input will only be used as strings inside the PHP file and not somehow as valid code?