简体   繁体   中英

Put config variables into php file

The system I'm working on has its own installation page to configure database connection. Basically, the user is filling some $_POST fields like host, dbname, password etc.. then once he proceed further I want to store all of this variables in a file.

The final file should goes like this:

<?php
    $config["db"]["host"] = "host";
    $config["db"]["username"] = "user";
    $config["db"]["password"] = "user_pass";
 ?>

But no matter what, the output is like this:

<?php
    $config["db"]["host"] = "";
    $config["db"]["username"] = "";
    $config["db"]["password"] = "";
?>

So it seems that all data from last quotes disappears. This is my code:

$file = 'core/database.core.php';

    $content = "<?php \r\n";
    $content .= '$config["db"]["host"] = "' . $_POST['db_host'] . '";' . "\r\n";
    $content .= '$config["db"]["username"] = "' . $_POST['db_user'] . '";' . "\r\n";
    $content .= '$config["db"]["password"] = "' . $_POST['db_pass'] . '";' . "\r\n";
    $content .= "?>";

file_put_contents($file, $content);

Var dump of $content variable outputs only this:

string(114) ""

The source code in browser show this:

string(114) "<?php 
$config["db"]["host"] = "127.0.0.1";
$config["db"]["username"] = "";
$config["db"]["password"] = "";
?>"

I've been trying in many ways and I have no idea how can i figure it out to work properly the way i want to achieve. Any suggestions?

Try to use var_export();

    $config["db"]["host"] = $_POST['db_host'];
    $config["db"]["username"] = $_POST['db_user'];
    $config["db"]["password"] = $_POST['db_pass'];

  $content = "<?php ".PHP_EOL." \$config = ".var_export($config,true)."; ".PHP_EOL." ?>";

If that wont work, check first if all fields are set right!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM