Generate file and save into new directory using PHP

Posted on Posted in PHP

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.

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

$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.

file_put_contents($dir_path."/file_name.html", $content);
file_put_contents($dir_path."/file_name.php", $content);
file_put_contents($dir_path."/file_name.txt", $content);

Here, file_name is the expected name of your file and $content is the the data that you want to save in the file.

Leave a Reply

Your email address will not be published. Required fields are marked *

15 + 5 =