Introduction:
Creating a new page in PHP is actually a lot easier than you think. Using a few simple functions and a form, you can create virtually any kind of file, assuming you have the correct permissions of course.
<html> <body> <form action="addfile.php" method="post"> <p>File name - <input type="text" name="file_name" /> <p> <p>File Extension: <select name="file_ext"> <option value=".php">PHP</option> <option value=".txt">Text</option> <option value=".html">HTML</option> <option value=".js">JavaScript</option> </select> </p> <p> <input type="submit" name="submit" value="Submit!" /> </p> </body> </html>
Explanation - addfile.html:
The addfile.html page is just a simple form that allows us to name the new page and select the extension. Pretty much self explanatory
.
[php]<?php
if(isset($_POST['submit'])) //has the form been submitted?
{
$file_directory = "/files/"; //the directory you want to store the new file in
$file_name = strip_tags($_POST['file_name']);//the file's name, stripped of any dangerous tags
$file_ext = strip_tags($_POST['file_ext']); //the file's extension, stripped of any dangerous tags
$file = $file_directory.$file_name.$file_ext; //this is the entire filename
$create_file = fopen($file, "w+"); //create the new file
if(!$create_file)
{
die("There was an error creating/opening the file! Make sure you have the correct permissions!\n");
}
$chmod = chmod($file, 0755); //set the appropriate permissions.
//attempt to set the permissions
if(!$chmod)
{
echo("There was an error changing the permissions of the new file!\n"); //error changing the file's permissions
}
//attempt to write basic content to the file
if (fwrite($create_file, "Content goes here!") === FALSE) {
echo "Error writing to file: ($file)\n";
}
fclose($create_file);
echo "File was created successfully!\n"; //tell the user that the file has been created successfully
exit; //exit the script
}else{ //the form hasn't been submitted!
header("Location: addfile.html"); //redirect the user back to the add file page
exit; //exit the script
}
?>[/php]