2012-05-22 59 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

相關問題