How to write PHP-Code inside fwrite() ?
Hello, in my Code i want to create a new .php file using php: fwrite(). How can I write PHP inside the fwrite() - function. My previous tries ended in errors because the PHP Code is executed and not "written" inside the created file ($fp).
This is my Code:
$fp=fopen('../blogs/'.$url.'.php','w');
fwrite($fp, "
<p>This is a paragraph</p>
<?php
$conn = mysqli_connect('server', 'username', 'password', 'database');
if(!$conn){
echo '<h3 class='container bg-dark p-3 text-center text-warning rounded-lg mt-5'>Not able to establish Database Connection<h3>';
}
// Get data to display on index page
$sql = 'SELECT * FROM blog WHERE id = $id';
$result = $conn->query($sql);
while($row = $result_->fetch_assoc()){
$content = $row['content'];
echo $content;
" ?>
I can display variables using $var inside the written file. But how do I just write the php code inside the $fp - file without executing it before?
Thanks for every help :)
As you can see with syntax highlight on this site, all variables in your generated string (e.g. $conn
, $sql
) are understand by PHP as variables in string. When PHP runs your code, these variable in string will be expanded (i.e. replaced by actual values) before fwrite() is run.
You may check your output PHP file to verify. All the variables are replaced by non-sense or simply disappeared. What you want to do is to have the variable name left as is (with the dollar sign and all) and write to the file.
This is explained by the documentation about PHP string parsing:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are 2 ways to fix this:
$
with \$
) in the double quote string.'
with \'
) to prevent accidentally ended the string quote.There are more issues than this with your generated code (For example the class
attribute uses single quote, which also ended your single-quote string and causes syntax error in the generated code). But if I fix all the code for you, I'd make this site a free code writing service, which this isn't.
To further debug, simply open the generated PHP file and check what syntax error it has. You may use editor that supports syntax checking (e.g. VSCode with PHP Intelephence). Or you may simply use php -l <filename>
. Fix them one by one by tweaking how you generated it.