Search code examples
phpinstallationfwrite

fwrite user DB info to file during Install


Im trying to create an installation wizard for my app. In one of the steps im trying to write/store the users connection details to a file. Does anyone know of a better way to do this. My code obviously breaks when it reaches the $ symbol.

    $myFile = "../functions/config2.php";
    $fh = fopen($myFile, 'w') or die("can't open file");

    $stringData = "<? #DATABASE CONNECTIONS\n";
    fwrite($fh, $stringData);

    $stringData = "$dbservertype='mysql';\n";
    fwrite($fh, $stringData);

    $stringData = "$servername='".$_POST['host']."';\n";
    fwrite($fh, $stringData);

    $stringData = "$dbusername='".$_POST['dbusername']."';\n";
    fwrite($fh, $stringData);

    $stringData = "$dbpassword='".$_POST['dbpass']."';\n";
    fwrite($fh, $stringData);

    $stringData = "$dbname='".$_POST['dbname']."';\n";
    fwrite($fh, $stringData);

    $stringData = "global $link;\n";
    fwrite($fh, $stringData);

    $stringData = "$link=mysql_connect ('$servername','$dbusername','$dbpassword');\n";
    fwrite($fh, $stringData);

    $stringData = "if(!$link){die('Could not connect to MySQL');}\n";
    fwrite($fh, $stringData);

    $stringData = "mysql_select_db('$dbname',$link) or die ('could not open db'.mysql_error());\n";
    fwrite($fh, $stringData);

    fclose($fh);

I would like the written file to end up looking something like this

    <?
    //DATABASE CONNECTIONS
    $dbservertype='mysql';
    $servername='posted_server';
    $dbusername='posted_user';
    $dbpassword='posted_pass';
    $dbname='posted_dbname';

    global $link;
    $link=mysql_connect ("$servername","$dbusername","$dbpassword");
    if(!$link){die("Could not connect to MySQL");}
    mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
    ?>

My output right now looks like this

    <? #DATABASE CONNECTIONS
    ='mysql';
    ='host';
    ='user';
    ='pass';
    ='dbname';
    global ;
    =mysql_connect ('','','');
    if(!){die('Could not connect to MySQL');}
    mysql_select_db('',) or die ('could not open db'.mysql_error());

Solution

  • You are using double quotes " in php if you include something that is a valid variable name in double quotes, php will interpolate that variable, and if it doesnt exist, it will resolve to nothing, or throw an error. See here

    You should escape the $ sign eg:

    $stringData = "\$dbservertype='mysql';\n";