0

First off, I'm trying to make sure that I'm not showing my MySQL password in my index page's source code. I've determined that making a "mysql.conf" file with the information I need will be sufficient.

Here is the section of code, pre-conf file. This worked without any problems:

$dbhost = "mysql.host.com";
$dbuser = "username";
$dbpass = "password";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

Now, here is the configuration file's contents (mysql.conf):

mysql.host.com
username
password

And the corresponding changes to the code...

$dbConfig = file("./config/mysql.conf");
$dbhost = $dbConfig[0];
$dbuser = $dbConfig[1];
$dbpass = $dbConfig[2];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

However, with the changes to use the configuration file, the MySQL connection now fails, giving me this error response:

"Could not connect: Access denied for user 'username'@'chain-lightning.dreamhost.com' (using password: YES)"

What am I missing? I've triple-checked that the text in the configuration file is the same as when I used static strings. Thanks!

3
  • first of all, php code will not render in page source code Commented Jan 20, 2017 at 7:24
  • and if you want to define constant you can use php.net/manual/en/function.parse-ini-file.php link to define constants Commented Jan 20, 2017 at 7:28
  • mysql_ is deprecated kindly use mysqli_ or PDO Commented Jan 20, 2017 at 7:45

1 Answer 1

1

The error you are getting mostly because of the data getting from file is not as you think. all your value will be added with extra newline value.

from http://php.net/manual/en/function.file.php

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.

use trim function with your variable it will work fine.

$dbConfig = file("./config/mysql.conf");
$dbhost = trim($dbConfig[0]);
$dbuser = trim($dbConfig[1]);
$dbpass = trim($dbConfig[2]);

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

or you can use FILE_IGNORE_NEW_LINES flag in file function

$dbConfig = file("./config/mysql.conf", FILE_IGNORE_NEW_LINES);
$dbhost = $dbConfig[0];
$dbuser = $dbConfig[1];
$dbpass = $dbConfig[2];

$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
Sign up to request clarification or add additional context in comments.

1 Comment

Good point! I will give this a try when I get back home. I resorted to using a config.php file and defining my variables, which works as well. If this solved the problem, I will accept this answer. Thank you for the response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.