PHP: fopen to create folders

本小妞迷上赌 提交于 2019-12-17 18:12:57

问题


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


回答1:


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);
}



回答2:


fopen doesn't create or open folders, only files. You should check with is_dir first if it exists, if not create it. mkdir has a recursive create option.

if (!is_dir($myDir)) {
    mkdir($myDir, 0777, true); // true for recursive create
}

If you are looking for a way to open a dir and read it's content you should look at SPL's DirectoryIterator




回答3:


you can't use fopen to create folders.
To create a folder you have to use mkdir

for the operations you have to repeat every time, there is a language feature called "user-defined functions". Least known feature of PHP, as one can say judging by stackoverflow answers.



来源:https://stackoverflow.com/questions/5337854/php-fopen-to-create-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!