2012-08-03 46 views
1

我正在構建一個小型的基於php的應用程序,它需要一個包含用戶名和密碼的「config.php」文件。而不是要求最終用戶在將應用程序上傳到服務器之前手動修改「config.php」,我想從設置表單動態生成「config.php」。如何通過PHP表單生成「config.php」?

基本上,我想用這個:

<form method="POST" action="?setup-config"> 
<fieldset> 
    <div class="clearfix"> 
     <label for="username">Desired User Name</label> 
     <div class="input"> 
      <input type="text" name="username" id="username"> 
     </div> 
    </div> 
    <div class="clearfix"> 
     <label for="password">Desired Password</label> 
     <div class="input"> 
      <input type="password" name="password" id="password"> 
     </div> 
    </div> 
    <div class="actions"> 
     <input type="submit" value="Save Username &amp; Password"> 
    </div> 
</fieldset> 
</form> 

打造 「config.php文件」:

<?php 

$username = 'entered username'; 
$password = 'entered password'; 
+0

使用['frwite()'](http://php.net/manual/en/function.fwrite.php) – 2012-08-03 17:19:46

+1

什麼?不,不,不,不,不。用戶名和密碼屬於數據庫。期。密碼需要通過散列來保證。 – Matt 2012-08-03 17:20:12

+1

@Matt - 我原則上同意,但在文件系統中爲小應用程序存儲用戶登錄數據沒有任何問題,只要(a)在文檔根目錄之外;和(b)你散列密碼數據(如你所提到的) – 2012-08-03 18:21:56

回答

2

我建議file_put_contents()

$config[] = "<?php"; 
$config[] = "\$username = '$_POST['username']';"; 
$config[] = "\$password = '$_POST['password']';"; 

file_put_contents("config.php", implode("\n", $config)); 
+0

你沒有使用正確的操作符。你需要使用concatination操作符:'。='...否則你只需在配置文件中有'$ config ='\ $ password ='$ _POST ['password']';'\ n「'。 – 2012-08-03 18:08:31

+0

確實,更新爲使用我的首選語法。我更喜歡數組和implode的可伸縮性,雖然這種小規模的東西,拼接變量會很好。 – 2012-08-03 18:13:05

+0

我也喜歡'file_put_contents()'方法 – 2012-08-03 19:22:31

1

一個非常基本的例子。這可以改善很多

<?php 
$fp = fopen('config.php', 'w'); 
fwrite($fp, "<?php\n"); 
fwrite($fp, "\$username = '$_POST['username']';\n"); 
fwrite($fp, "\$password = '$_POST['password']';\n"); 
fclose($fp); 
?>