Wednesday, July 31, 2019

php - Warning: mysql_connect(): Access denied




i have this php function to read my dbinfo out of a textfile on my pc:



function loaddb(){
$fh = fopen('dta.txt','r');
$line = fgets($fh);
$_SESSION['dbname']=$line;

$line = fgets($fh);
$_SESSION['dbuser']=$line;


$line = fgets($fh);
$_SESSION['dbpass']=$line;

$line = fgets($fh);
$_SESSION['server']=$line;
fclose($fh);
};


and this code works. but when it returns my code into my session var i see it has added extra line breaks in the actual variable, so the result when i connect is





Warning: mysql_connect(): Access denied for user 'root



'@'localhost' (using password: YES) in
C:\Users\Jacques\Dropbox\Jacques\Web\Code.php on line 37 Could not
connect: Access denied for user 'root



'@'localhost' (using password: YES)





how can i fix this. i have tried replacing all character return and spaces but it doesnt help



this is the text in my textfile




dbname



root




password



localhost:3306



Answer



If you're sure that the whitespaces are on each end of the string, you can use trim()



$_SESSION['dbname']= trim($line);



When you're dealign with a string that can have several spaces, you can solve that with a simple regular expression:



$regex = '/(\s)\s+/'; // Select a whitespace and following whitespaces
$str = preg_replace($regex, '$1', $str); // Replace with the first whitespace








Saving your database credentials in a text file in your www folder is a very bad practise. If someone happens to find the filename he can read your credentials.



PHP code however is parsed before sent to the client, thus client's can't access the credentials (unless you echo them).



config.php



define('DB_HOST', 'localhost:3306');
define('DB_NAME', 'dbname');
define('DB_USER', 'root');

define('DB_PASS', 'password');


Then, whenever you need your database credentials:



require 'config.php';
// connect here






Another sidenote



The mysql_ functions are deprecated as of PHP 5.5.0. You should use mysqli_ or PDO instead. I prefer PDO myself.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...