Reputation: 5
I am creating file in php by using fwrite
. I need to attach the database to my index.php
My doubt is can I print the below line on fwrite
? I have tried it but it shows error. Is there any way for this?
$fd =fopen("database.php","w");
fwrite($fd, "$dbhost='localhost';
$dbuser='$user';
$dbpass='$pass';
$dbname='$email';
$dbh = new PDO('mysql:host=localhost;dbname=$email', $dbuser, $dbpass);");
fclose($fd);
Upvotes: 0
Views: 102
Reputation: 542
It's showing errors because the variables aren't escaped. To fix this issue, either swap out the quote markes with single quote marks or add a backslash () infront of $.
$fd=fopen("database.php","w");
fwrite($fd,"\$dbhost='localhost';
\$dbuser='\$user';
\$dbpass='\$pass';
\$dbname='\$email';
\$dbh=newPDO('mysql:host=localhost;dbname=\$email',\$dbuser,\$dbpass);");
fclose($fd);
Or the quote mark fix:
fwrite($fd, '$dbhost="localhost";
$dbuser="$user";
$dbpass="$pass";
$dbname="$email";
$dbh = new PDO("mysql:host=localhost;dbname=$email", $dbuser, $dbpass);');
Both should work.
If you want to pass variables to the text (like $user, $pass, $email), don't escape them.
$fd=fopen("database.php","w");
fwrite($fd,"\$dbhost='localhost';
\$dbuser='$user';
\$dbpass='$pass';
\$dbname='$email';
\$dbh=newPDO('mysql:host=localhost;dbname=$email',\$dbuser,\$dbpass);");
fclose($fd);
Quote version:
fwrite($fd, '$dbhost="localhost";
$dbuser="' . $user . '";
$dbpass="' . $pass . '";
$dbname="' .$email . '";
$dbh = new PDO("mysql:host=localhost;dbname=' . $email . '", $dbuser, $dbpass);');
Upvotes: 1
Reputation: 46
What error(s) do you get? Did you declare all the vars?
If you do $dbuser='$user' between "", then php thinks the vars already exist, so if they don't you get errors.
The thing you are trying is not really possible.
Upvotes: 0