In tutrorials for Connecting to MySQL with PHP you see something similar to the below.
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'myuser','mypassword');
I have a connection working this way on my localhost but for putting it live what do you do about the password? Do you just leave it as plain text like that in your php file? Or is there a more secure way to handle this?
解决方案
Nobody can see your connection string if they look at the source, it can only be seen by looking at your raw code. I would also have it inside a separate file, and include the file on your page. This also helps if you need to change the password, as you won't have to edit every page that uses a connection - you'll only need to edit the one file.
Alternatively, you can have a connection string in an include file and place it outside of document root. This stops people getting to this file using a browser or if they attack your FTP. This will help security of your plain-text passwords, but is still accessible if somebody gets/has access to your local directories. To do this, you may need to configure a PHP configuration variable, open_basedir, which allows your script to talk to a file outside of root. This all depends on if you have access to a folder behind root of course, and if you can change that configuration variable.
Other than that, there's not much that can be done.
Include File Example:
Create a file called conn.php and store your connection in there.
$dbConn = mysql_connect($host, $user, $pass);
mysql_select_db("dbName", $dbConn);
On the page that needs the connection, include the conn.php file like so:
include("conn.php");
if (!dbConn) {
die('Sorry, our database did not load. Please try again later.');
exit();
}
$result = mysql_query("...");
?>