Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write php code to a file with php

Tags:

php

fwrite

For part of my website I need to be able to write php code to a file with php. For example:

$filename = "RtestR.php";
$ourFileName =$filename;
$ourFileHandle = fopen($ourFileName, 'w');



$written =  "
    <html>
    <body>
    <?php
    echo \"I like the color \".$_SESSION['color'].\"!!!!\";
    </body>
    </html>

";

fwrite($ourFileHandle,$written);

fclose($ourFileHandle);

But, instead of creating the file, it throws this error:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 14

What am I doing wrong and what is the right way to write php code to a file?
EDIT:
I think I might need to make myself clearer... I want the SESSION to be determined when the newly created file is loaded. Technically I don't want to get the session on this page, but instead on the page I am creating!!! I want to write the code to the file, not the output of the code!

like image 949
pattyd Avatar asked Jun 10 '13 17:06

pattyd


1 Answers

Finally figured this out! I needed to escape my $ symbols! Like this:

$written =  "
<html>
<body>
<?php
echo \"I like the color \".\$_SESSION['color'].\"!!!!\";
</body>
</html>

";

Can't believe i didn't think of that ;)
Thank you all!

like image 97
pattyd Avatar answered Oct 11 '22 06:10

pattyd