Search code examples
phpfwrite

fwrite php script into a file


Basically, I can write html tags/text etc etc to the file. All that is fine. However, I need to be able to write some actual php into the file and I'm completely oblivious of how I should go about doing this.

Anyway here is what I have got to help better demonstrate my situation:

$path = substr(md5(time() . md5(rand())), 0, 8);
$dir = substr(md5($_SERVER['REMOTE_ADDR']), 0, 4);
$fpath = "b/" . $dir "/" . $path;
$file = 'index.php';

$handle = fopen($fpath . '/' . $file, 'w') or die ('cannot create the file'); 
include template.php;
fwrite($handle, $pt1 . $pt2 . $pt3);

Inside the template.php I have variables holding a lot of html in $pt1,$pt2,$pt3 But, inbetween each 'pt' I need to have some actuall php.

So for example sake say I need $this inbetween each 'pt' and the $this being:

<?php 
if(isset($_SESSION['user'])){
echo "hello";
}else{
echo "bye";
} 
?>

How would I do it?

*The actual creating of the file and paths is fine though but, I know that it may look very unusual however, I like it that way. It's simply adding the php scripts to the php file.

  • also I have tried sticking the scripts inside variables but, it seems to just print them out as plain text in the file rather than executing them.

Solution

  • Does inbetween each pt means $p1 . $var . $pt2?

    Try something like this:

    <?PHP
    $var = '<?php 
    if(isset($_SESSION["user"])){
    echo "hello";
    }else{
    echo "bye";
    } 
    ?>';
    echo $pt1 . $var . $pt2;
    ?>
    

    Edit:

    Also, you can wrap long content into a variable using

    <?PHP
    $var = <<< 'PHP'
    <?php 
    if(isset($_SESSION["user"])){
    echo "hello";
    }else{
    echo "bye";
    } 
    ?>
    PHP;
    $pt1 = 'before';
    $pt2 = 'after';
    echo "$pt1 $var $pt2";
    ?>