【问题标题】:Edit PHP file using another PHP file and add a line on top of it使用另一个 PHP 文件编辑 PHP 文件并在其顶部添加一行
【发布时间】:2013-03-02 01:13:24
【问题描述】:

我有一个 PHP 文件,我想在需要时动态添加行。

假设我有 foo.php 里面有这些:

<?php

echo "foo!";

?>

但我希望能够添加我在另一个文件中指定的行作为要添加到其顶部的变量并保存旧内容,如下所示:

<?php

echo "bar!";

echo "foo!";

?>

每当我运行添加顶行的其他文件时,无论如何我都希望它添加这一行:

echo "bar!";

所以如果我运行它两次,文件将是这样的:

<?php

echo "bar!";

echo "bar!";

echo "foo!";

?>

我知道安全问题并且文件将受到保护,我只是不知道最好的方法是什么,fopen?卷曲?请帮我找出最好的方法来做到这一点。谢谢

【问题讨论】:

  • file_get_contents() 编辑 file_put_contents()

标签: php dynamic line fopen updates


【解决方案1】:
$a = explode("\r\n", file_get_contents('file')); 
array_splice($a, 1, 0, array('echo \'whatever\';'));
$a = implode("\r\n", $a);
file_put_contents('file', $a);

更简单:

$a="<?php\r\necho 'whatev';\r\n".substr($a,7);

【讨论】:

  • 无论如何,我都会为遇到此答案/问题的经验不足的 PHP 开发人员添加此评论:modifying or generating PHP scripts via scripting is 非常危险只有在你真正知道自己在做什么以及可能的后果时才这样做
猜你喜欢
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多