skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Some advice

    1. It seems pointless to have dynamic PHP as cache (if that’s what it is). If you have to write static HTML cache, you’d better off doing that by writing the actual HTML output (.html).
    2. If you have to keep the page dynamic and also want to cache, there are better way to caching then to create static files for all your pages. Learn to use composer then search Packagist for solution.
    3. Even if you don’t care about the above 2 points, you should do mysqli_connect() by including a common script. MySQL information would change from time to time. If it happens to you, you’d have to modify a lots of file with your approach.

    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:

    When a string is specified in double quotes or with heredoc, variables are parsed within it.

    There are 2 ways to fix this:

    1. Escape all the dollar signs (i.e. replace $ with $) in the double quote string.
    2. Use single quote in your fwrite. In which case, you have to escape all the single quote (i.e. replace ' 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search