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
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
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
<?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.
Did you check like this :
$_SESSION['dbname'] = trim($line);
Use trim()
:
$_SESSION['dbname']= trim($line);
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:"
- " " (ASCII 32 (0x20)), an ordinary space.
- "\t" (ASCII 9 (0x09)), a tab.
- "\n" (ASCII 10 (0x0A)), a new line (line feed).
- "\r" (ASCII 13 (0x0D)), a carriage return.
- "\0" (ASCII 0 (0x00)), the NUL-byte.
- "\x0B" (ASCII 11 (0x0B)), a vertical tab.
http://php.net/manual/en/function.trim.php