2012-05-22 60 views
2

我正在处理应该替换另一个文件中的变量的文件。到目前为止,我尝试过:我可以在另一个文件中替换吗?

$File = "$dir/submit.php"; 
$fh = fopen($File, 'r') or die("Couldn't edit the Config-file. Please report to admin."); 
$chosendb = str_replace('$chosendb = comments;','$chosendb = wuhuws_$dir;','$chosendb'); 
fclose($fh); 

$ dir是一个用户输入。 注释是数据库中需要用prefix_ $ dir替换的表。

我该怎么做?

+3

你甚至还没有从文件中读取。你只是打开了一个句柄。 [使用'file_get_contents()'](http://us3.php.net/manual/en/function.file-get-contents.php)将其读入字符串。然而,看到@zerkms这不是一个好主意,开始... –

+2

@zerkms,应*不* *! – bfavaretto

+0

@zerkms怎么回事? :) – Christian

回答

2

你忘了再次写入文件。

// Read the file 
$content = file_get_contents("$dir/submit.php"); 

// Do the editing 
$content = str_replace('$chosendb = comments;','$chosendb = wuhuws_$dir;', $content); 

// Save the file 
file_put_contents("$dir/submit.php", $content); 

然而,正如Zerkms说(或至少打算;-)),它通常是一个坏主意用PHP编辑PHP,特别是因为你会发现一个困难时期后调试脚本因为它的代码在运行时动态改变。

是否有任何理由,你为什么不能包含这个文件,手动设置这些变量,如:

// Include the file  
require("$dir/submit.php"); 
// Edit the variable 
$chosendb = "wuhuws_$dir"; 
+0

我该怎么做? :) – Christian

+0

请查看我更新的答案。 – Zar

+0

我会看看它。谢谢:) – Christian

相关问题