How to create file in different directory in PHP

Let’s imagine I want to create a file in a different folder than where I am in the current moment. How to create this file in the different folder? This article will help with a small piece of code achieve creation of a file in the different folder.

First of lets have a folder structure like this:

root
  index.php
  create
    page.php

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

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

<?php 

$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) . ").";
}
This entry was posted in Uncategorized. 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.