How to create a file in a different directory in PHP

How to make this file in another folder than the execution file location? This article will help you with a small snippet of code to create a file in a different folder.

First of lets have a folder structure like this:

root_folder/
root_folder/index.php
root_folder/create/
root_folder/create/page.php

Let’s imagine I want to create a file in a different folder from the folder of php execution file.

I am currently in the root folder, executing the php file in index.php. In this file, I want to run a certain function which will create me a new file in the predefined folder.

If you want to be sure that the folder into which you want to export the file exists, check our recent post about creating new folders.

Here is a code that will create a new file in a predefined location.

$fileContent = 'This is the content in the file.';
$fileName = 'page.txt';
$filePath = './create/'.$fileName;

if (file_put_contents($filePath, $fileContent) !== false) {
    echo "File created (" . basename($filePath) . ").";
} else {
    echo "Cannot create the file (" . basename($filePath) . ").";
}

Conclusion

This small article has shown how to create this file in a different folder rather than the execution file location.

This entry was posted in Language basics and tagged , . Bookmark the permalink.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.