PHP: fopen to create folders


The fopen can’t be used to create directories. This is because fopen function doesn't create or open folders, it only works with files.

Before using the fopen function, one should check with is_dir first if it exists, if not create it using the mkdir function −

$filename = '/path/to /file.txt';
$dirname = dirname($filename);
if (!is_dir($dirname)) {
   mkdir($dirname, 0755, true);
}

The above code creates a path to the file named ‘filename’. The directory of the ‘filename’ is obtained using the ‘dirname’ function. Next, this directory is checked for the existence using the ‘is_dir’ function. If the directory already exists, no operation takes place. On the other hand, if the directory doesn’t exist, it is created using the ‘mkdir’ function by passing specific access rights.

Updated on: 09-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements