2013-07-04 22 views
0

我有如下原型如何使一個模式修飾符替換iin php文件中的值?

<?php 
$config['some_key']='some_value'; 
$config['some_other_key']='some_other_value'; 

//End of file config.php 

我有獲取和顯示這些變量對管理員的值的文件,然後他改變一些設置,如果他希望這樣的文件。所以我必須更新config.php文件以保存更改。例如some_value必須改變以new_value這樣的:

<?php 
$config['some_key']='new_value'; 
$config['some_other_key']='some_other_value'; 

//End of file config.php 

我研究了一點,發現了我的一個選項是使用file_get_contents()讀取文件使用preg_replace()申請我的變化寫文件再次,但我不知道如何做一個模式和替代我的目的。 我真的很感謝你們的幫助,提前致謝。

+0

無論是讀取還是寫入ini/xml/json文件或使用數據庫,您都無法得到更好的服務嗎? –

+0

我使用codeigniter,並有配置文件和讀取這些文件的配置類,通常的方式來更新codeigniter中的配置文件是打開文件並手動更改它,我想要做的是爲它 – Nero

+0

然後你可以使用一個數據庫來存儲這些值,並有一個鉤子來加載那裏的設置和'get_instance() - > config-> set_item()'它們。也許是[像這樣](http://stackoverflow.com/questions/10674341/reading-codeigniter-config-values-from-database-instead-of-config-file)。 – complex857

回答

0

如果您不介意文件的格式發生變化,您可以使用var_export()使其更加健壯。此功能將導出你的$config變量的格式如下:

array (
    'some_key' => 'some_value', 
    'some_other_key' => 'some_other_value', 
) 

在代碼的一部分,其中管理頁面有張貼的變化,你可以做這樣的事情:

// load in the config file 
include 'config.php'; 
// now you will have a local $config variable from the file 

// update the config array with the data posted by the user 
foreach ($_POST['changes'] as $key => $value) { 
    $config[$key] = $value; 
} 
// write the $config variable back to the file 
file_put_contents('config.php', '$config = '.var_export($config, true)); 

中當用戶直接在應用程序中編寫可執行代碼的過程對惡意用戶具有可怕的安全隱患。

+0

感謝您的答案,但我使用鉤子,因爲你建議,它的作品像一個魅力,再次感謝 – Nero

相關問題