PHP: fopen 创建文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5337854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:04:14  来源:igfitidea点击:

PHP: fopen to create folders

phpdirectoryfopen

提问by Vivek

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

如果路径不存在,我需要知道是否有任何方法可以创建新文件夹。当我尝试 fopen() 路径时,它说NO such File or Directory exists我尝试使用“w”和“w+”打开文件,但无法创建新文件夹。有没有办法在不使用 mkdir() 的情况下实现它。因为我每次都需要从 mkdir() 的路径中单独提取目录名称。任何帮助表示赞赏。谢谢...

回答by qbert220

fopen cannot create directories.

fopen 无法创建目录。

You'll need to use something like:

你需要使用类似的东西:

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

回答by ChrisR

fopen doesn't create or open folders, only files. You should check with is_dirfirst if it exists, if not create it. mkdirhas a recursive create option.

fopen 不创建或打开文件夹,只创建文件。您应该is_dir首先检查它是否存在,如果不存在则创建它。mkdir有一个递归创建选项。

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

如果您正在寻找一种打开目录并阅读其内容的方法,您应该查看 SPL 的DirectoryIterator

回答by Your Common Sense

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

您不能使用 fopen 创建文件夹。
要创建文件夹,您必须使用 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.

对于每次都必须重复的操作,有一种称为“用户定义函数”的语言功能。PHP 最不为人所知的特性,正如从 stackoverflow 的答案判断的那样。