如何从另一个文件编辑PHP文件,如Wordpress install.PHP文件


How I can edit a PHP file from another file, like the Wordpress install.php file?

我正试图为我的CMS创建一个安装脚本,但我不知道如何。。。

我希望我的脚本将config.php中的$var设置为输入的值。

类似:

<?php
$file = config.php
$file_handle = fopen($file, "rw");
fwrite($file_handle, "$settings1 = ".$_POST['settings1']);
fclose($file_handle);
?>

这是工作还是我用了坏方法?因为我试过了,但没用。。。

执行此操作的方法是将配置文件解析为一个变量,解析它并更改解析数据中的设置,然后将文件重写回覆盖旧文件的文件。

如果这是你自己的cms,并且你正在创建系统,我会选择像$settings['key']=$value这样的数组配置;或者,您也可以创建ini文件,并使用php的内置函数来解析和重写数据。

这是我使用了很长时间的方法,它对我有效。

示例

以下是Zend Framework组件Zend_Config_Writer的用法示例:(http://zendframework.com/manual/en/zend.config.writer.introduction.html)

$config = new Zend_Config_Ini('config.ini',
                          null,
                          array('skipExtends'        => true,
                                'allowModifications' => true));
// Modify a value
$config->production->hostname = 'foobar';
// Write the config file
$writer = new Zend_Config_Writer_Ini(array('config'   => $config,
                                       'filename' => 'config.ini'));
$writer->write();

它们有ini、xml、yaml和原生php数组的组件。明智的做法是将其纳入您的cms或研究他们使用的方法。

希望能有所帮助,

Jay

file_put_contents('/path/to/config.php', "$settings1 = ".clean($_POST['settings1']), FILE_APPEND | LOCK_EX);

并注意许可。

快速且肮脏
需要编辑的文件:

$i_am_a_var = [I AM A PLACE HOLDER NUMBER 4];

这是安装脚本:

$c=file_get_content('file_to_edit.php');
$c=str_replace('[I AM A PLACE HOLDER NUMBER 4]',"'zimbabue the new value'",$c);
file_put_content('file_to_edit.php',$c);

我建议您使用.ini文件进行配置。它们非常容易阅读(例如,看看parse_ini_file())。写它们有点困难,但我仍然认为它比你试图做的更容易

此外,您还可以将JSON文件与JSON_encode()和JSON_decode()一起用于此类目的,因为对于它们,您已经完成了读取和写入此类文件的功能。