Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: fopen to create folders

I need to know if there is any way to create new folder if the path doesn't exist. When I try to fopen() a path, it says NO such File or Directory exists I tried to open the file using 'w' and 'w+' but it is not able to create new folder. Is there any way to achieve it without using mkdir(). Because I need to extract the directory names alone from the path to mkdir() everytime. Any help is appreciated. Thanks...

like image 399
Vivek Avatar asked Mar 17 '11 10:03

Vivek


People also ask

Does fopen create directory PHP?

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. The above code creates a path to the file named 'filename'. The directory of the 'filename' is obtained using the 'dirname' function.

Can PHP create folders?

You can create a directory with PHP using the mkdir() function. mkdir("/path/to/my/dir", 0700); You can use fopen() to create a file inside that directory with the use of the mode w .

What does fopen () function do in PHP?

The fopen() function opens a file or URL.

Does fopen create a new file?

The fopen function creates the file if it does not exist.


1 Answers

fopen cannot create directories.

You'll need to use something like:

$filename = '/path/to/some/file.txt'; $dirname = dirname($filename); if (!is_dir($dirname)) {     mkdir($dirname, 0755, true); } 
like image 165
qbert220 Avatar answered Sep 28 '22 05:09

qbert220