2012-08-03 66 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); 
?>