tags:

views:

313

answers:

4

Hi all,

I am wondering if it is possible to write php code to a file. For example:

fwrite($handle, "<?php $var = $var2 ?>");

I would like it produce the exact string in the file and not the eval'ed code. Is this possible?

I am currently getting the following output (where $var = 1 and $var2 = 2):

<?php 1 = 2 ?>

Whereas I want the actual string:

<?php $var = $var2 ?>

Thanks for the help

+16  A: 

You can use single quotes instead of double quotes, which do not expand inline variable names:

fwrite($handle, '<?php $var = $var2 ?>');
Joey
A: 

This has nothing to do with file io. Read about variable substitution and escaping in strings in PHP.

+3  A: 

double quoted strings are parsed for variables, and the variables value is inserted at that position. i suppose this is because php originally was designed as a thin webserver-database templating layer.

personally, i don't like that and never use double quotes because of this. instead, i always use single quotes and string concenation:

<?php echo 'hello, ' . $name; ?>

does the same as:

<?php echo "hello, $name"; ?>

single quotes: syntax coloring works better, it's (marginally) faster and errors are found easier

Schnalle
+2  A: 

Just escape the $ symbol

<?php
fwrite($handle, "<?php \$var = \$var2 ?>");
?>
PERR0_HUNTER