php 运行 file_put_contents() 时创建文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13372179/
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
Creating a folder when I run file_put_contents()
提问by Jake
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.
在我尝试了这个之后,我得到了错误结果。
Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory
消息:file_put_contents(upload/promotions/201211/ang232.png):无法打开流:没有这样的文件或目录
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?
有没有办法解决这个问题?
回答by Jason McCreary
file_put_contents()does not create the directory structure. Only the file.
file_put_contents()不创建目录结构。只有文件。
You will need to add logic to your script to test if the monthdirectory exists. If not, use mkdir()first.
您需要向脚本添加逻辑以测试月目录是否存在。如果没有,mkdir()请先使用。
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);
Update:mkdir()accepts a third parameter of $recursivewhich will create anymissing directory structure. Might be useful if you need to create multiple directories.
更新:mkdir()接受第三个参数,$recursive该参数将创建任何丢失的目录结构。如果您需要创建多个目录,可能会很有用。
Example with recursive and directory permissions set to 777:
递归和目录权限设置为 777 的示例:
mkdir('upload/promotions/' . $month, 0777, true);
回答by aqm
modification of above answer to make it a bit more generic, (automatically detects and creates folder from arbitrary filename on system slashes)
修改上述答案以使其更通用,(自动检测并从系统斜杠上的任意文件名创建文件夹)
ps previous answer is awesome
ps 以前的答案很棒
/**
* create file with content, and create folder structure if doesn't exist
* @param String $filepath
* @param String $message
*/
function forceFilePutContents ($filepath, $message){
try {
$isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
if($isInFolder) {
$folderName = $filepathMatches[1];
$fileName = $filepathMatches[2];
if (!is_dir($folderName)) {
mkdir($folderName, 0777, true);
}
}
file_put_contents($filepath, $message);
} catch (Exception $e) {
echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
}
}
回答by Manojkiran.A
i have Been Working on the laravel Project With the Crud Generator and this Method is not Working
我一直在使用 Crud Generator 处理 laravel 项目,但这种方法不起作用
@aqm so i have created my own function
@aqm 所以我创建了自己的函数
PHP Way
PHP方式
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!file_exists($directoryPathOnly))
{
mkdir($directoryPathOnly,0775,true);
}
file_put_contents($fullPathWithFileName, $fileContents);
}
LARAVEL WAY
拉维尔方式
Don't forget to add at top of the file
不要忘记在文件顶部添加
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\File;
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!File::exists($directoryPathOnly))
{
File::makeDirectory($directoryPathOnly,0775,true,false);
}
File::put($fullPathWithFileName,$fileContents);
}
回答by Nicky Smits
I wrote a function you might like. It is called forceDir(). It basicaly checks whether the dir you want exists. If so, it does nothing. If not, it will create the directory. A reason to use this function, instead of just mkdir, is that this function can create nexted folders as well.. For example ('upload/promotions/januari/firstHalfOfTheMonth'). Just add the path to the desired dir_path.
我写了一个你可能喜欢的函数。它被称为 forceDir()。它基本上检查您想要的目录是否存在。如果是这样,它什么都不做。如果没有,它将创建目录。使用这个函数而不只是 mkdir 的一个原因是这个函数也可以创建 nexted 文件夹.. 例如 ('upload/promotions/januari/firstHalfOfTheMonth')。只需将路径添加到所需的 dir_path 即可。
function forceDir($dir){
if(!is_dir($dir)){
$dir_p = explode('/',$dir);
for($a = 1 ; $a <= count($dir_p) ; $a++){
@mkdir(implode('/',array_slice($dir_p,0,$a)));
}
}
}

