Jump to content

[SOLVED] Creating a File


genics

Recommended Posts

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?

 

 

Link to comment
https://forums.phpfreaks.com/topic/49609-solved-creating-a-file/
Share on other sites

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.