运行file_put_contents()时创建一个文件夹 [英] Creating a folder when I run file_put_contents()
问题描述
我从网站上上传了很多图像,需要以更好的方式组织文件. 因此,我决定按月创建一个文件夹.
I have uploaded a lot of images from the website, and need to organize files in a better way. Therefore, I decide to create a folder by months.
$month = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
尝试了这一步之后,我得到了错误结果.
after I tried this one, I get error result.
消息:file_put_contents(upload/promotions/201211/ang232.png):无法打开流:没有这样的文件或目录
Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory
如果我尝试仅将文件放入"existant"文件夹中,则可以正常工作.但是,它无法创建新文件夹.
If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.
有没有办法解决这个问题?
Is there a way to solve this problem?
推荐答案
file_put_contents()
不会创建目录结构.只有文件.
file_put_contents()
does not create the directory structure. Only the file.
您将需要在脚本中添加逻辑以测试 month 目录是否存在.如果不是,请先使用 mkdir()
.
You will need to add logic to your script to test if the month directory exists. If not, use mkdir()
first.
if (!is_dir('upload/promotions/' . $month)) {
// dir doesn't exist, make it
mkdir('upload/promotions/' . $month);
}
file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
更新:mkdir()
接受$recursive
的第三个参数,它将创建 any 缺少的目录结构.如果您需要创建多个目录,可能会很有用.
Update: mkdir()
accepts a third parameter of $recursive
which will create any missing directory structure. Might be useful if you need to create multiple directories.
将递归和目录权限设置为777的示例:
Example with recursive and directory permissions set to 777:
mkdir('upload/promotions/' . $month, 0777, true);
这篇关于运行file_put_contents()时创建一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!