Writing PHP file not working

半城伤御伤魂 提交于 2019-12-14 03:29:57

问题


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.


回答1:


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);



回答2:


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

PHP-tags are parsed.




回答3:


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?




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/17956090/writing-php-file-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!