Monday, 9 October 2017

php - Warning: mysql_connect(): Access denied

itemprop="text">

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 href="http://php.net/manual/en/function.trim.php"
rel="nofollow">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 href="http://www.php.net/manual/en/ref.mysql.php" rel="nofollow">mysql_
functions are deprecated as of PHP 5.5.0. You should use href="http://php.net/manual/en/book.mysqli.php" rel="nofollow">mysqli_ or
PDO
instead. I prefer PDO myself.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...