genics Posted May 2, 2007 Share Posted May 2, 2007 Hi genii, I'm trying to create a PHP script to create a PHP script within a seperate PHP file. Using the following: $db_name = $_POST['db_name']; $db_user = $_POST['db_user']; $db_pass = $_POST['db_pass']; $data = "<?php $host = 'localhost'; $user = $db_user; $pass = $db_pass; $name = $db_name; $access = mysql_connect($host, $user, $pass) or die('Could Not Connect.'); mysql_select_db($name) or die('Database Not Found.'); ?>"; $file = "connect.php"; if (!$file_handle = fopen($file,"a")) { echo "Cannot open file. "; } if (!fwrite($file_handle, $data)) { echo "Cannot write to file. "; } fclose($file_handle); I want to create a working connection script depending on the variables set in a previous form. My output is: <?php = 'localhost'; = test; = test; = test; = mysql_connect(, , ) or die('Could Not Connect.'); mysql_select_db() or die('Database Not Found.'); ?> Can anyone help me? Quote Link to comment https://forums.phpfreaks.com/topic/49609-solved-creating-a-file/ Share on other sites More sharing options...
chronister Posted May 2, 2007 Share Posted May 2, 2007 <?php $db_name = 'testname'; $db_user = 'testuser'; $db_pass = 'testpassword'; $data = '<?php $host = \'localhost\'; $user = \''.$db_user.'\'; $pass = \''.$db_pass.'\'; $name = \''.$db_name.'\'; $access = mysql_connect($host, $user, $pass) or die(\'Could Not Connect.\'); mysql_select_db($name) or die(\'Database Not Found.\'); ?>'; $file = "connect.php"; if (!$file_handle = fopen($file,"a")) { echo "Cannot open file. "; } if (!fwrite($file_handle, $data)) { echo "Cannot write to file. "; } fclose($file_handle); ?> You have to make the data var a literal string. The variables you want to use as variables have to be escaped and concatenated properly. This works perfectly for me. It outputs: newly created connect.php <?php $host = 'localhost'; $user = 'testuser'; $pass = 'testpassword'; $name = 'testname'; $access = mysql_connect($host, $user, $pass) or die('Could Not Connect.'); mysql_select_db($name) or die('Database Not Found.'); ?> Note that this script appends to the end of the file. If it is ran more than once in a directory you will get duplicates you might want to try fopen($file,"w+") so that if it already exists, it will open for reading and writing, truncate the file to zero length, and place the pointer at the beginning of the file Nate Quote Link to comment https://forums.phpfreaks.com/topic/49609-solved-creating-a-file/#findComment-243245 Share on other sites More sharing options...
genics Posted May 2, 2007 Author Share Posted May 2, 2007 Brilliant! Thanks Nate :-) Quote Link to comment https://forums.phpfreaks.com/topic/49609-solved-creating-a-file/#findComment-243493 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.