dongmi4734 2013-12-14 16:36
浏览 47
已采纳

从另一个PHP文件创建PHP文件插入变量[复制]

This question already has an answer here:

I am actually creating a PHP script, and it requires some database connection, it shall require the config.php file that contains Database details like this

$dbname = "coolsix"; 
$dbhost = "localhost"; 

Now, i dont want the users to create the file themselves, i want my install.php to create the file, but it is not inserting the details, i did this

if($_POST["submit"]) 
{//Retrieve form values
    $db_type=$_POST["db_type"];
    $db_name=$_POST["db_name"]; 
    $db_user=$_POST["db_user"];
    $db_host=$_POST["db_host"]; 
    $db_pass=$_POST["db_pass"];

    //Write 
    $my_file = '../config.php'; 
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); 
    $data = '<?php  //PHP Downloader Configuration File global $config, $db; ?> <?php $dbhost = ".$db_host.";<br> $dbname = ".$db_name.";<br> $dbuser = ".$db_user.";<br> $dbpass = ".$db_pass.";<br> ?>'; 
    fwrite($handle, $data);

The config.php file is created, but it does not contain the values, it contains the variables, i expect it to replace $dbname with the value the user specify in the installation form. see the form http://loadedgeek.com/downloader/inis

Any idea?

</div>
  • 写回答

1条回答 默认 最新

  • dpoppu4300 2013-12-14 17:06
    关注

    You actually have a few problems. First, you need to use double-quotes so your variable substitution happens correctly. Second, you want to escape the $varname with a backslash when you don't want the substitutions to happen. Third, you have to account for the fact that people might have quotes inside their usernames, passwords, etc..

    A simple way to build the string you want would be...

    $db_type=addslashes($_POST["db_type"]);
    $db_name=addslashes($_POST["db_name"]); 
    $db_user=addslashes($_POST["db_user"]);
    $db_host=addslashes($_POST["db_host"]); 
    $db_pass=addslashes($_POST["db_pass"]);
    
    $content = "<?php 
        \$dbhost = '$db_host';
        \$dbname = '$db_name';
        // etc...
    ";
    
    file_put_contents($my_file, $content);
    

    That general technique will work okay, most of the time.

    A better way is to use an actual template library. That way, you can make use of purpose-built filters that properly escape strings, neaten up the text, and put the template of the config file you are building in a separate file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。