Search code examples
phpfwritewritefile

Use PHP fwrite to write php file


I'm building a CMS and I'm stuck on this problem. I need to write a simple php file for every page and I need to pass an ID and the include function. Here is my code to write the file:

 $filename=mysqli_fetch_array($query))['pagename'];
    $fw=fopen("../".$filename,'w',true);
    fwrite( "<php 
                \$id = $id;
                include('admin/renderpage.php');
            ?>");
    fclose($fw);

and this is the result, which looks like what I need, only that the variable $id is not an actual variable and include function doesn't work either.

<php 
            $id = 2;
            include('admin/renderpage.php');
            ?>

Solution

  • Try:

    $filename=mysqli_fetch_array($query))['pagename'];
    $fw=fopen("../".$filename,'w',true);
    fwrite( $fw, "<?php 
                \$id = $id;
                include('admin/renderpage.php');
            ?>");
    fclose($fw);
    

    The PHP open tag is: <?php not <php. PHP tags