编写PHP文件不起作用

时间:2013-07-30 19:50:33

标签: php fwrite

我正在尝试使用fwrite()函数动态编写PHP文件,但它似乎没有用。代码肯定是在写入的字符串中,但是当我打开写入的文件时,它就不存在!我的假设是PHP编译器无论出于何种原因读取字符串中的PHP标记,执行它们之间的内容,然后放弃它们。这个假设准确吗?我该怎么做才能解决它?

代码看起来像这样:

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

我在'code'变量周围尝试了单引号和双引号。

编辑:我尝试过单引号,但随后单引号变量与双引号变量混合并转换它。我感到愚蠢。抱歉浪费了每个人的时间。

5 个答案:

答案 0 :(得分:0)

尝试以下操作,以便PHP不解析字符串的内容(单引号):

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

答案 1 :(得分:0)

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

解析PHP标签。

答案 2 :(得分:0)

您可能遇到了许可问题。我得到了这个工作。检查使用:

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

?>

print_r是否有任何意义?

答案 3 :(得分:0)

我有同样的问题,结果我需要使用绝对路径, 参考this solution

答案 4 :(得分:0)

您需要在字符串周围加上小写引号。你不希望PHP解析它,你想要乱丢那个字符串。此外,还有另一个功能,file_put_contents()

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

此函数与连续调用fopen(),fwrite()和fclose()以将数据写入文件相同。

Be ware :您正在玩一个危险的游戏,编写其他PHP文件。你最好110%确定你正在做什么,然后对你采取的每一步进行双重/三重检查。无论你做什么,都有一种更安全的方式。