slavkovicdjordje
slavkovicdjordje

Reputation: 19

Making directory in php

I have a problem when I want to upload pictures and to make new directory which does not exist it doesnt make folder $gallery_name, it store pictures in uploads/galerije/$username instead of uploads/galerije/$username/$gallery_name. Can anyone help me?

$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";
    }
}

Upvotes: 0

Views: 138

Answers (3)

Nick Savage
Nick Savage

Reputation: 876

You need to tell mkdir() to create the directories recursively if they're not already existant.

Try passing true to your mkdir() function:

mkdir($desired_dir, 0777, true); 

The php documents specifically state that mkdir() doesn't deal with recursive directories by default, as of 5.0.0 you can pass in the argument to change that

Upvotes: 5

Kamiccolo
Kamiccolo

Reputation: 8497

According to PHP documentation:

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

so, to create directories recursively You might do like this:

mkdir("$desired_dir", 0777, true);

Upvotes: 2

federicot
federicot

Reputation: 12341

You are using is_dir here:

if(is_dir("$desired_dir/".$file_name)==false){

When you should use file_exists. Maybe that's part of your problem.

Upvotes: 2

Related Questions