在运行 file_put_contents() 时创建一个文件夹

php
2022-08-30 08:26:53

我从网站上上传了很多图像,需要以更好的方式组织文件。因此,我决定按月创建一个文件夹。

$month  = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);

在我尝试这个之后,我得到错误结果。

消息:file_put_contents(上传/促销/201211/ang232.png):无法打开流:没有此类文件或目录

如果我尝试只将文件放在存在文件夹中,它的工作原理。但是,它无法创建新文件夹。

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


答案 1

file_put_contents() 不创建目录结构。仅文件。

您需要向脚本添加逻辑以测试月份目录是否存在。如果没有,请先使用 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);

更新:接受第三个参数,该参数将创建任何缺少的目录结构。如果需要创建多个目录,则可能很有用。mkdir()$recursive

递归和目录权限设置为 777 的示例:

mkdir('upload/promotions/' . $month, 0777, true);

答案 2

修改上述答案以使其更加通用,(自动检测并从系统斜杠上的任意文件名创建文件夹)

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

推荐