Local Tech Repair: Creating a PHP Page From Another PHP Page

Sunday, November 6, 2011

Creating a PHP Page From Another PHP Page

Some times it is good to know how to create other PHP pages from with in a PHP script. This can especially be helpful in a configuration file for setting up a program.

creating files should not be hard to do if you know how to use fopen, fwrite functions in PHP. Though for those that are starting out in programming in PHP escape characters are sometimes tricky.

Lets look at a simple example. Lets say we need our install script to take the mysql server host, username, password, and the prefix for the tables that it creates. Though you need to keep this information so that the server can remember to how to connect to the mysql server. An easy way is creating a php script that is used to connect to the mysql server. So this is an example of how a script may look
Configure.php:

$db_name = "localtechrepair";
$username = "localtechrepairuser";
$password = "samplepassword";
$host = "localhost";
$prefix = "LTC_";

/*
* **********************************************************
* Creats a file with stored info for database connection
* **********************************************************
*/
$filename = "connect.php";
$filenamehandle = fopen($filename, 'w') or die("can't create connection file please make sure you have write permissions");
$connectdata = "
";
if (fwrite($filenamehandle, $connectdata)) {echo "Created Connect file...";} else {echo "Error: Can't Create connect.php file"; exit;}
fclose($filenamehandle);



What this does is allow your program to remember all the information that the user put in while and writing it to a file. once this script runs it will create a fully functional php connection script that you can include in your other scripts so that you don't have to write it on all your scripts which would take a lot of extra editing.

For those that are new to escape characters the \ before the $ or " means that it is supposed to be text not a variable. we do this instead of using ' single quote because we want variables in the print out. Using escape character also help with not having to break this text up in in many different appending text variables.

If you have any suggestions or find a mistake please comment.
Local Tech Repair Admin

No comments:

Post a Comment