-3

I'm trying to dynamically write PHP files using the fwrite() function and it just does not seem to be working. The code is definitely in the string being written, but then when I open the file that was written it just isn't there! My assumption is that the PHP compiler is, for whatever reason, reading the PHP tags in the string, executing what's between them, and then abandoning them. Is this assumption accurate? What can I do to get around it?

The code looks something like this:

$code = "<?php echo \"This is a dynamically written file!\"; ?>";
$openFile = fopen("filename.php","w");
fwrite($openFile,$code);
fclose($openFile);

I have tried both single and double quotes around the 'code' variable.

EDIT: I tried single quotes, but then the single-quoted variable was mixing with a double-quoted variable and converting it. I feel dumb. Sorry for wasting everybody's time.

user2597300
  • 43
  • 1
  • 7

5 Answers5

0

Try the following so PHP doesn't parse the content of your string (single quotes):

$code = '<?php echo "This is a dynamically written file!"; ?>';
$openFile = fopen("filename.php","w");
fwrite($openFile,$code);
fclose($openFile);
Remko
  • 968
  • 6
  • 19
  • I was not the one who downvoted you, for the record. You were right, while I did say I tried that it was a situational problem and I didn't give enough detail. I was then mixing the single quoted string with a double quoted string. – user2597300 Jul 30 '13 at 20:01
0

$code = "<"."?php echo \"This is a dynamically written file!\"; ?".">";

PHP-tags are parsed.

Robert de W
  • 316
  • 8
  • 24
0

You are likely having permission issues. I got this to work. To check use:

<?php

$code = "<?php echo \"This is a dynamically written file!\"; ?>";
$openFile = fopen("filename.php","w");

print_r(error_get_last());

fwrite($openFile,$code);
fclose($openFile);

?>

Does print_r yeild anything?

Kirk Backus
  • 4,776
  • 4
  • 32
  • 52
0

I had the same issue, turned out I need to use absolute path, refer to this solution

Krishna Modi
  • 377
  • 2
  • 12
0

You need to put litteral quotes around the string. You dont want PHP to parse it, you want litterly that string. Also, there is another function for that, file_put_contents():

$code = '<?php echo "This is a dynamically written file!"; ?>';
$openFile = file_put_contents("filename.php");

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

Be ware: You're playing a dangerous game, writing other PHP files. You better be 110% sure what you're doing and double/triple check every step you take. Whatever it is you're doing, there is a safer way.

Martijn
  • 15,791
  • 4
  • 36
  • 68