2012-02-11 110 views
0

如何更新php文件中的變量並將其保存到磁盤?我試圖做一個小的CMS,在一個文件,沒有數據庫,我希望能夠更新配置變量,我做了一個設置頁面,當我更新我想變量更新在php文件中。 下面會更新變量,但當然不會將它保存到php文件中,那麼我該怎麼做?PHP如何更新php文件中的變量

<?php 
$USER = "user"; 
if (isset($_POST["s"])) { $USER = $_POST['USER']; } 
?> 
<html><body> 
Current User: <?php echo $USER; ?> 
<form method="post" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>"> 
New User<input type="text" name="USER" value="<?php echo $USER; ?>"/> 
<input type="submit" class="button" name="s" value="Update" /> 
</form> 
</body></html> 

我不知道我是否錯過了明顯的? 我想用這樣的事情的:

$newcms = file_get_contents(index.php) 
str_replace(old_value, new_value, $newcms) 
file_puts_contents(index.php, $newcms) 

但它似乎並不像正確的解決方案......

+0

林困惑,你需要更好地解釋自己你想要做什麼 – JimmyBanks 2012-02-11 23:40:07

回答

1

作爲一個更好的方法,你可以有一個單獨的文件只是爲了設置和將該文件包含在PHP文件中。然後,您可以根據需要更改和保存其值,而不必修改PHP文件本身。

+0

是的,這將是一個解決方案,但這也將帶走一個文件CMS的概念,我真的很喜歡在一個文件中完成整個事情...... – oiZo 2012-02-11 23:46:41

2

最簡單的方法是將它們序列化到磁盤,然後加載它們,所以你可能有這樣的事情:

<?php 

    $configPath = 'path/to/config.file'; 
    $config = array(
    'user' => 'user', 
); 

    if(file_exists($configPath)) { 
    $configData = file_get_contents($configPath); 
    $config = array_merge($defaults, unserialize($configData)); 
    } 

    if(isset($_POST['s']) { 
     // PLEASE SANTIZE USER INPUT 
     $config['user'] = $_POST['USER']; 

     // save it to disk 
     // Youll want to add some error detection messagin if you cant save 
     file_put_contents($configPath, serialize($config)); 
    } 
?> 

<html><body> 
Current User: <?php echo $config['user'; ?> 
<form method="post" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>"> 
New User<input type="text" name="USER" value="<?php echo $config['user']; ?>"/> 
<input type="submit" class="button" name="s" value="Update" /> 
</form> 
</body></html> 

這種方法使用PHP的心不是這非常可讀的原始序列化格式。如果您希望手動更新配置或更輕鬆地檢查配置,則可能需要使用不同的格式,如JSON,YAML或XML。通過使用json_encode/json_decode而不是serialize/unserialize,JSON可能幾乎可以快速且容易地使用。 XML會更慢,更麻煩。 YAML也很容易處理,但你需要一個外部庫,如sfYaml

此外,我不會只是做一個腳本的頂部,ID可能使它的一個類或一系列的功能至少。

0

例如,你有YOURFILE.php,和裏面你有$targetvariable='hi jenny';

,如果你想改變這個變量,然後使用此:

<?php 
$fl='YOURFILE.php'; 
     /*read operation ->*/ $tmp = fopen($fl, "r"); $content=fread($tmp,filesize($fl)); fclose($tmp); 

// here goes your update 
$content = preg_replace('/\$targetvariable=\"(.*?)\";/', '$targetvariable="hi Greg";', $content); 
     /*write operation ->*/ $tmp =fopen($fl, "w"); fwrite($tmp, $content); fclose($tmp); 
?>