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>
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.