运行file_put_contents()时创建文件夹

时间:2022-04-13 16:47:21

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?

有没有办法解决这个问题?

3 个解决方案

#1


101  

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 month directory 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 $recursive which will create any missing 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);

#2


8  

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

#3


-3  

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

#1


101  

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 month directory 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 $recursive which will create any missing 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);

#2


8  

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

#3


-3  

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