Create directory if not exists else move file

I have the following code to upload a file:

<?php
//set the image size in mb
$max_upload_size='10';
$MAXIMUM_FILESIZE = $max_upload_size * 1024 * 1024;
get_current_user();
global $current_user;
$uploaddir = './uploads/file/'.$current_user->user_login.'/'; 
$file = $uploaddir . basename($_FILES['uploadfile']['name']); 
if ($_FILES['uploadfile']['size']<$MAXIMUM_FILESIZE) {
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
  echo "success"; 
} else {
    echo "error";
}
}else{
    echo"size_error";
}
?>

This works great if the user_login already exists under /uploads/file/ directory. How can I create the directory that is based on variable $current_user->user_login if it doesn’t exists? If exists then continue on the next code.

Related posts

Leave a Reply

2 comments

  1. From http://nz.php.net/manual/en/function.move-uploaded-file.php#105026:

    The destination directory must exist; move_uploaded_file() will not automatically create it for you.

    Just use is_dir and mkdir.

    <?php
    //set the image size in mb
    $max_upload_size='10';
    $MAXIMUM_FILESIZE = $max_upload_size * 1024 * 1024;
    global $current_user;
    $current_user = get_current_user();
    $uploaddir = './uploads/file/'.$current_user->user_login.'/';
    if (!is_dir($uploaddir) && !mkdir($uploaddir)){
      die("Error creating folder $uploaddir");
    }
    $file = $uploaddir . basename($_FILES['uploadfile']['name']); 
    if ($_FILES['uploadfile']['size']<$MAXIMUM_FILESIZE) {
    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
      echo "success"; 
    } else {
        echo "error";
    }
    }else{
        echo"size_error";
    }
    ?>
    
  2.   <?php
    //set the image size in mb
    $max_upload_size='10';
    $MAXIMUM_FILESIZE = $max_upload_size * 1024 * 1024;
    get_current_user();
    global $current_user;
    if(!is_dir('./uploads/file/'.$current_user->user_login))
    {
       mkdir('./uploads/file/'.$current_user->user_login);
    }
    $uploaddir = './uploads/file/'.$current_user->user_login.'/'; 
    $file = $uploaddir . basename($_FILES['uploadfile']['name']); 
    if ($_FILES['uploadfile']['size']<$MAXIMUM_FILESIZE) {
    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
      echo "success"; 
    } else {
        echo "error";
    }
    }else{
        echo"size_error";
    }
        ?>
    

    Or after $updloaddir initialization add if statement with $uploaddir parameter in is_dir() and mkdir().