In this lesson we will see how to generate file and save into new directory using PHP. So we will generate a HTML, PHP or any other type of file and save it into a newly created or existed directory.
Step 1: At first we have to select an existing directory or create a new directory by using mkdir() function.
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.com/ */ $dir_path = "depth1/depth2/depth3"; mkdir($dir_path, 0777, true); ?>
Here, $dir_path is the path to the expected directory/folder of your hard drive.
And ’0777′ is the default permission of the folder/file (widest possible access).
So, the file will be located in this directory: current_directory/depth1/depth2/depth3
But if you want to create the folder outside the current directory, then use “../” for each level you want to go back for the new directory.
For example, if your current directory is “C:\xampp\htdocs\cd” and you want to create the new folder inside “xampp” folder then you have to write like the following-
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.com/ */ $dir_path = "../../test"; mkdir($dir_path, 0777, true); ?>
So, path for the new directory will be “C:\xampp\test”.
Step 2: After creating the directory simply put the generated file to the directory by using file_put_contents() function.
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.com/ */ file_put_contents($dir_path."/name-of-file.html", $content); file_put_contents($dir_path."/name-of-file.php", $content); file_put_contents($dir_path."/name-of-file.txt", $content); ?>
Here, name-of-file is the expected name of your file and $content is the the data that you want to save in the file.