1

I have a txt file which contains the log in credentials separated by newline. I want to pick up data from that file and set the connection string according to that. Here's the code for that.

$db = array(3);
$myFile = "sqlaccess.txt";  
$handle = fopen($myFile, 'r');  
if(!feof($handle))
{
    for($i=0;$i<4;$i++)  
    {  
         $db[$i] = fgets($handle);  
         echo $db[$i];  echo "<br>"; 
    }
}
else
{
     fclose($handle); 
}    
$dbhost = $db[0];
$dbuser = $db[1]; 
$dbpass = $db[2]; 
$dbname = $db[3]; 

the echo command displays everything correctly as saved in the file. Now the connection string is:

$conn = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname);  

This is not working. Connection fails

but connection is succesful if i hard code this as follows:

$conn = mysqli_connect('localhost','root','password', 'Newdb');

but hardcoding is not a good practice. so What could be going wrong in my code??

6
  • Sidenote: I hope you are using proper precautions to guard that text file. Plus, is there a particular reason as to why you would want to use such a method? Commented Nov 19, 2014 at 13:59
  • Have you made sure that $db has a value in every index referenced? Commented Nov 19, 2014 at 14:00
  • There should be $db[$i] = trim(fgets($handle)); Commented Nov 19, 2014 at 14:02
  • You could just use file() which will return a file as an array, instead of all that extra fopen/for code. Commented Nov 19, 2014 at 14:03
  • @Fred-ii- Yes I am encrypting that file and decrypting back for reading it. There's no perticular reason as to why I am using this method. I am just learning and trying these things in php. Commented Nov 21, 2014 at 4:20

1 Answer 1

1

fgets will not strip \n from the returned string, so you either need to trim them yourself:

$db[$i] = trim(fgets($handle));

Or use the file function to replace your read loop:

$db = file('sqlaccess.txt');

If you choose the latter, your code is simplified to:

$myFile = 'sqlaccess.txt';
$db = file($myFile);

$dbhost = $db[0];
$dbuser = $db[1];
$dbpass = $db[2];
$dbname = $db[3];
Sign up to request clarification or add additional context in comments.

3 Comments

@Sean Bright Thanks alot. I thot "\0" is causing trouble. Thanks for clearing that up!
Please don't encourage bad practices such as these in the future. While it's a useful answer, he's looking to do something and thinks this is how to do it.
@iWontStop I appreciate your concern. I am not doing this professionally. Its just for fun. Moreover reading the login credentials from a ".properties" file (instead of hard-coding the credentials as in your method) is a good practice I guess. I will try your method also later. Its my learning phase man. CALM DOWN!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.