mkdir():文件存在(Yii2)

时间:2018-10-01 07:51:31

标签: yii2

尝试创建新目录时出现此错误。我不明白的是,当我使用$folderGallery = mkdir($dir.$modelGallery->gallery_id, 0777, true);时,它不起作用,但是当我更改为$modelGallery->gallery_name时,它已成功创建。

$session = Yii::$app->session;

$modelGallery= new Gallery();

//die(count($modelEulogy));

if ($modelGallery->load(Yii::$app->request->post())) 
{
    if($modelGallery->validate())
    {
        $dir = 'img/'.$session['UserID'].'/album/';

        //die($modelGallery->gallery_id);

        if(!file_exists($dir))
            $folderGallery = mkdir($dir.$modelGallery->gallery_id, 0777, true);
        else
            $folderGallery = mkdir($dir.$modelGallery->gallery_id, 0777, true);


        //$model->gallery_id = $id;
        $modelGallery->user_id = $session['UserID'];
        $modelGallery->date = date("Y-m-d H:i:s");
        $modelGallery->save();
    }
    return $this->redirect(['index', 'gallery_id'=>$id]);
}

2 个答案:

答案 0 :(得分:0)

您必须检查现有目录

$path = $dir.$modelGallery->gallery_id;
if (!is_dir($path)) {
    mkdir($dir.$modelGallery->gallery_id, 0777, true);
}

答案 1 :(得分:0)

您可以使用FileHelper::createDirectory()-它会为您做任何必要的检查。您还应该使用绝对路径,以避免路径解析不明确:

$dir = '@webroot/img/'.$session['UserID'].'/album/';
FileHelper::createDirectory(Yii::getAlias($dir . $modelGallery->gallery_id, 0777, true));