Writing php code using fopen, fwrite, fclose

When defining a file containing php code which is trying to create a .php file containing php code, it seems that trying to write variables, like $A or $B, isn’t as simple as I would assume.
Take the following example: (content of some php file:)

$myfile = fopen(“newfile.php”, “a”) or die(“Unable to open file!”);
$txt = “<?php\n”;
fwrite($myfile, $txt);
$txt = “function formule(’$A’,’$B’)\n”;
fwrite($myfile, $txt);
$txt = “{\n”;
fwrite($myfile, $txt);
$txt = " ‘$result’=0;\n";
fwrite($myfile, $txt);
$txt = " $result = ‘$A’+’$B’;\n";
fwrite($myfile, $txt);
$txt = " return ‘$result’;\n";
fwrite($myfile, $txt);
$txt = “};\n”;
fwrite($myfile, $txt);
$txt = “echo formule(2,3);\n”;
fwrite($myfile, $txt);
$txt = “?>\n”;
fwrite($myfile, $txt);
fclose($myfile);
include_once(“newfile.php”);

It will output this:

<?php function formule('','') { ''=0; = ''+''; return ''; }; echo formule(2,3); ?>

instead of what I am trying to achieve:

<?php function formule($A,$B) { $result=0; $result=$A+$B; return $result; }; echo formule(2,3); ?>

Why?

Because when you have a variable ($variable) inside a string surrounded by double quotes, it will try to get the value stored in the variable. If you want to actually output $a, you must either surround the string in single quotes, or escape the dollar sign.

// Option 1
$txt = "function formule('\$A', '\$B')";
// Option 2
$txt = 'function formule(\'$A\', \'$B\')';

You use a backslash (\) to escape characters. In option 1, we’re escaping the dollar sign, to avoid getting the variable value. In option 2, we’re escaping the single quote, which would end the string.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service