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
Did you check like this :
Use
trim()
:From the docs:
"This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:"
http://php.net/manual/en/function.trim.php
If you're sure that the whitespaces are on each end of the string, you can use
trim()
When you're dealign with a string that can have several spaces, you can solve that with a simple regular expression:
Important sidenote
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
Then, whenever you need your database credentials:
Another sidenote
The mysql_ functions are deprecated as of PHP 5.5.0. You should use mysqli_ or PDO instead. I prefer PDO myself.