JohnDow
JohnDow

Reputation: 1332

Ignore PHP code inside PHP variable

I want to generate connector.php file during installation like this

$file = "connector.php";
$fp = fopen($file,"wb");

$content = "<?php $con=mysqli_connect('";
$content += $host;
$content += "', '";
$content += $user;
$content += "', '";
$content += $password;
$content += "', 'blog');  if (mysqli_connect_errno()) { echo 'Failed to connect to MySQL: ' . mysqli_connect_error(); }?>";

fwrite($fp,$content);
fclose($fp); 

but when I try this code, I just generate empty file (when I try some random text, it works fine), so I think, the problem is, that PHP trying to interpret everything between <?php and ?>. How can I make this code work, and make PHP not interpret code between php tags.

Upvotes: 0

Views: 832

Answers (2)

Amal
Amal

Reputation: 76636

+= is a numeric operator and .= is a string operator. You're currently using += in your code and it will cause PHP to interpret it as a number.

The + or += operator first converts the values to integers (and all strings evaluate to zero when cast to ints) and then adds them, so you get 0. That's why your code isn't producing the expected result.

See ComFreek's answer above.

Also, an unrelated issue: to tell PHP not to use the actual variable values in the string, simply escape them, like so:

$content = "<?php \$con=mysqli_connect('";

Or, you can use single quotes:

$content = '<?php $con=mysqli_connect(\'';

reference: #2202331

Upvotes: 4

ComFreek
ComFreek

Reputation: 29434

Use .= as concatenation operator.

Using + probably converts the whole thing to an integer. You also have to use single quotes around the first line in the second code block because PHP tries to interpret the undefined variable $con otherwise.

$file = "connector.php";
$fp = fopen($file,"wb");

// Use single quotes here, otherwise PHP tries to interpret $con
$content = '<?php $con=mysqli_connect(\'';
$content .= $host;
$content .= "', '";
$content .= $user;
$content .= "', '";
$content .= $password;
$content .= "', 'blog');  if (mysqli_connect_errno()) { echo 'Failed to connect to MySQL: ' . mysqli_connect_error(); }?>";

fwrite($fp,$content);
fclose($fp); 

Upvotes: 4

Related Questions