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 🙂
2
Answers
What are you doing is uncommon and as other people said I advise you to look around for more consolidated an readymade solutions.
Anyway, the problem is that you are using double quotes that cause undesiderated expansion of variables.
To avoid this you can simply swap single quotes for double quotes in the main PHP code string you are writing.
(except for the row of error message <h3> which needs external quotes to be written as
'
)This practice is also needed for the
$sql = 'SELECT * FROM blog WHERE id = $id';
line to work (it must become$sql = "SELECT * FROM blog WHERE id = $id";
) – Although it’s not clear where the $id variable comes from.Also your string containing the code seems truncated
Some advice
You problem
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:
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.