使用fopen时mysql无法连接

The code below doesn't connect:

$file_open = fopen("logindetails.txt","r");

if($file_open){
    $user = fgets($file_open);
    $pass = fgets($file_open);
    $server = fgets($file_open);
}
echo "user: ",$user,"password: ",$pass,"server: ",$server;
@$db_handle = mysql_connect($server,$user,$pass);

but outputs:

user: root password: usbw server: localhost

logindetails.txt contains:

root
usbw
localhost

while this code connects:

$user = "root";
$pass = "usbw";
$server = "localhost";

echo "user: ",$user,"password: ",$pass,"server: ",$server;
@$db_handle = mysql_connect($server,$user,$pass);

I can't get this working and I can't guess why.

The variables you read with fgets in also contain linebreaks.

$user == "root
";
$pass == "passw
";

Which is why MySQL won't recognize them as valid.

So, you should either:

  • trim() them
  • instead use an INI file
  • better yet some config.php instead of a text file.