在php中创建目录

sla*_*dje 0 php

我有一个问题,当我想上传图片和创建一个不存在的新目录它不会使文件夹$ gallery_name,它存储上传/ galerije/$用户名的图片而不是uploads/galerije/$ username/$ gallery_name.谁能帮我?

$username = $_SESSION['username'];
$gallery_name = $_POST['gallery_name'];

if (isset($_FILES['files'])) {
    $errors = array();
    foreach ( $_FILES['files']['tmp_name'] as $key => $tmp_name ) {
        $file_name = $key . $_FILES['files']['name'][$key];
        $file_size = $_FILES['files']['size'][$key];
        $file_tmp = $_FILES['files']['tmp_name'][$key];
        $file_type = $_FILES['files']['type'][$key];

        if ($file_size > 2097152) {
            $errors[] = 'File size must be less than 2 MB';
        }

        $desired_dir = "uploads/galerije/" . $username . "/" . $gallery_name;

        if (empty($errors)) {
            if (!is_dir($desired_dir)) {
                mkdir($desired_dir, 0777); // Create directory if it does not exist
            }
            if (!is_dir("$desired_dir/" . $file_name) == false) {
                move_uploaded_file($file_tmp, "$desired_dir/" . $file_name);
                header("location: index.php");
            }
        }
        else {
            print_r($errors);
        }
    }
    if (empty($error)) {
        echo "Success";
    }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*age 5

如果它们尚未存在,您需要告诉mkdir()以递归方式创建目录.

尝试传递true给你的mkdir()函数:

mkdir($desired_dir, 0777, true); 
Run Code Online (Sandbox Code Playgroud)

PHP文件明确指出的mkdir()不与默认递归目录处理,为5.0.0,你可以在更改的参数传递