Mkdir file exists ошибка

The file transferring to my upload folder is working well but I have a warning in mkdir. It says file exist but the picture and folder generates own name. I don’t know what warning is determining.

include 'connect.php';

$dir = substr(uniqid(), -7); // Uniqid for subdirectory

$path = "uploads/$dir/"; // uploads/subdirectory/  // Make directory

$valid_formats = array("jpg", "png", "jpeg", "kml");

$max_file_size = 2097152;

$count = 0;

// Loop $_FILES to execute all files

if (!empty($_FILES)) {
    foreach ($_FILES['files']['name'] as $f => $name) {
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }

        if ($_FILES['files']['error'][$f] == 0) {
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            } elseif (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) {
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            } else { // No error found! Move uploaded files
                mkdir($path, 0700);
                $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
                $uniq_name = substr(uniqid(), -5) . '.' . $ext;
                $dest = $path . $uniq_name;

                if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
                    // more logic
                }
            }
        }
    }
}

By default, file management tools, such as ls, dir, or even the graphical file manager, don’t show hidden files or directories (those where the name begins with a dot, e.g. .ipython). This is why mkdir is telling you that it already exists, even though you cannot see it by using ls or the file manager.

To see hidden files, you can use ls -a (From the ls manpage : «-a, --all do not ignore entries starting with .«), or, in the graphical file manager (nautilus), press Ctrl + H to show hidden files and directories.

New Linux users often get puzzled by the “mkdir: cannot create directory” errors when taking first steps and trying to learn basics of working with files and directories. In this short post I’ll show the two most common types of this mkdir error and also explain how to fix things so that you no longer get these errors.

mkdir: cannot create directory – File exists

This should be self explanatory after a few weeks of using commands like mkdir, but the first time you see this it can be confusing.

File exists? How can it be when you’re just trying to create a directory? And why does it say “File exists” when you’re trying to create a directory, not a file?

This error suggests that the directory name you’re using (/tmp/try in my example shown on the screenshot) is already taken – there is a file or a directory with the same name, so another one can’t be created.

Consider this scenario:

[email protected]:~$ mkdir /tmp/try
mkdir: cannot create directory – File exists

You can use the wonderful ls command to check what’s going on:

[email protected]:~$ ls -ald /tmp/try
drwxr-xr-x 2 greys root 4096 Nov 5 18:55 /tmp/try

Sure enough, we have a directory called /tmp/try already!

The reason it says “File exists” is because pretty much everything in Unix is a file. Even a directory!

Possible solutions to mkdir: cannot create directory – file exists scenario

Rename (move) existing directory

Use the mv command to move /tmp/try into some new location (or giving it new name). Here’s how to rename /tmp/try into /tmp/oldtry:

[email protected]:~$ mv /tmp/try /tmp/oldtry

Let’s rerun the mkdir command now:

[email protected]:~$ mkdir /tmp/try

…and since there are no errors this time, we probably have just created the /tmp/try directory, as desired. Let’s check both /tmp/try and the /tmp/oldtry with ls:

[email protected]:~$ ls -ald /tmp/try /tmp/oldtry
drwxr-xr-x 2 greys root 4096 Nov 5 18:55 /tmp/oldtry
drwxrwxr-x 2 greys greys 4096 Nov 5 19:08 /tmp/try

Remove existing file

Another option you always have is to simply remove the file that’s blocking your mkdir command.

First, let’s create an empty file called /tmp/newtry and confirm it’s a file and not a directory usng ls command:

[email protected]:~$ touch /tmp/newtry
[email protected]:~$ ls -lad /tmp/newtry
-rw-rw-r-- 1 greys greys 0 Nov 5 20:50 /tmp/newtry

Now, if we try mkdir with the same name, it will fail:

[email protected]:~$ mkdir /tmp/newtry
mkdir: cannot create directory '/tmp/newtry': File exists

So, to fix the issue, we remove the file and try mkdir again:

[email protected]:~$ rm /tmp/newtry
[email protected]:~$ mkdir /tmp/newtry

This time there were no errors, and ls command can show you that indeed you have a directory called /tmp/newtry now:

[email protected]:~$ ls -lad /tmp/newtry
drwxrwxr-x 2 greys greys 4096 Nov 5 20:50 /tmp/newtry

mkdir: cannot create directory – Permission denied

This is another very common error when creating directories using mkdir command.

The reason for this error is that the user you’re running the mkdir as, doesn’t have permissions to create new directory in the location you specified.

You should use ls command on the higher level directory to confirm permissions.

Let’s proceed with an example:

[email protected]:/tmp$ mkdir try2018
[email protected]:/tmp$ mkdir try2018/anotherone
[email protected]:/tmp$ ls -ald try2018
drwxrwxr-x 3 greys greys 4096 Nov 5 21:04 try2018

All of these commands succeeded because I first created new directory called try2018, then another subdirectory inside of it. ls command confirmed that I have 775 permissions on the try2018 directory, meaning I have read, write and execture permissions.

Now, let’s remove the write permissions for everyone for directory try2018:

[email protected]:/tmp$ chmod a-w try2018
[email protected]:/tmp$ ls -ald try2018
dr-xr-xr-x 3 greys greys 4096 Nov 5 21:04 try2018

If I try creating a subdirectory now, I will get the mkdir: cannot create directory – permissions denied error:

[email protected]:/tmp$ mkdir try2018/yetanotherone
mkdir: cannot create directory 'try2018/yetanotherone': Permission denied

To fix the issue, let’s add write permissions again:

[email protected]:/tmp$ chmod a+w try2018
[email protected]:/tmp$ mkdir try2018/yetanotherone

As you can see, try2018/yetanotherone directory was successfully created:

[email protected]:/tmp$ ls -ald try2018/yetanotherone
drwxrwxr-x 2 greys greys 4096 Nov 5 21:05 try2018/yetanotherone

That’s it for today! Hope you liked this tutorial, be sure to explore more basic Unix tutorials on my blog.

See Also
Basic Unix commands
mkdir command in Unix
File types in Unix
chmod and chown
Unix commands tutorial

See also

  • Advanced Unix Commands
  • Basic Unix Commands
  • Unix Commands tutorial
  • chmod vs chown

Новички в Linux часто не понимают, что делать при получении ошибки “mkdir: cannot create directory” во время работы с командной строкой. Есть несколько причин возникновения такой ошибки, и в этом переводе своей англоязычной статьи с сайта Unix Tutorial я покажу эти причины и их устрание на примерах.

mkdir: cannot create directory – File exists

В переводе с английского сообщение означает: невозможно создать каталог — файл уже существует.

ФАЙЛ существует? А при чём тут проблема создания каталога? И почему ошибка говорить “существует файл”, когда мы вообще пытаемся создавать каталог, а не файл?

На самом деле всё просто: большинство объектов в Linux являются файлами и структурами в файловой системе. Поэтому эта ошибка означает, что там, где вы пытаетесь выполнить команду создания нового каталога, уже существует другой объект с таким же именем. В данном случае — это файл, а не каталог. Но у файла такое же имя, как у желаемого каталога, так что создать второй объект с таким же именем не получится.

Например, ошибка

[email protected]:~$ mkdir /tmp/try
mkdir: cannot create directory – File exists

намекает, что у нас уже есть файл с именем /tmp/try.

Очень просто проверить эту гипотезу с помощью команды ls:

[email protected]:~$ ls -ald /tmp/try
drwxr-xr-x 2 greys root 4096 Nov 5 18:55 /tmp/try

Так и есть, у нас существует файл с таким именем.

Возможные решения проблем mkdir: cannot create directory

Сценарий file exists

Если файл с таким именем уже существует, а каталог всё же очень хочется создать, то есть решения.

Переименовать (или переместить) существующий файл

Используем команду mv для перемещения /tmp/try в другой каталог (или просто сменим имя try на другое, оставив файл в том же каталоге /tmp).
Вот как можно переименовать файл в имя oldtry:

[email protected]:~$ mv /tmp/try /tmp/oldtry

Теперь давайте попробуем ту же команду mkdir:

[email protected]:~$ mkdir /tmp/try

…и всё замечательно работает! Никаких ошибок, и создался новый каталог под названием /tmp/try.
Подтверждаем это с помощью команды ls:

[email protected]:~$ ls -ald /tmp/try /tmp/oldtry
drwxr-xr-x 2 greys root 4096 Nov 5 18:55 /tmp/oldtry
drwxrwxr-x 2 greys greys 4096 Nov 5 19:08 /tmp/try

Удалить существующий файл

Ещё одна опция, которая напрашивается сама собой — можно просто удалить неугодный файл, который мешает созаднию нашего нового каталога.

Для этого примера создадим новый пустой файл с названием /tmp/newtry

[email protected]:~$ touch /tmp/newtry
[email protected]:~$ ls -lad /tmp/newtry
-rw-rw-r-- 1 greys greys 0 Nov 5 20:50 /tmp/newtry

Если попробовать mkdir, то получится ожидаемая ошибка:

[email protected]:~$ mkdir /tmp/newtry
mkdir: cannot create directory '/tmp/newtry': File exists

А теперь мы просто удалим неугодный файл и попробуем mkdir снова:

[email protected]:~$ rm /tmp/newtry
[email protected]:~$ mkdir /tmp/newtry

В этот раз нет никаких ошибок, всё снова сработало:

[email protected]:~$ ls -lad /tmp/newtry
drwxrwxr-x 2 greys greys 4096 Nov 5 20:50 /tmp/newtry

##mkdir: cannot create directory – Permission denied

Это — ещё один распространённый сценарий при создании каталогов.

В переводе на русский, сообщение говорит: невозможно создать каталог — недостаточно прав доступа.
То есть файлов с таким же именем нет, но текущий пользователь, под которым мы пытаемся создать каталог, не имеет прав в текущем месте файловой системы для создания новых каталогов (и файлов).

Основной подход к такой ошибке — проверка прав доступа в каталоге, где получена ошибка. Команда ls и здесь поможет.
You should use ls command on the higher level directory to confirm permissions.

Например:

[email protected]:/tmp$ mkdir try2018
[email protected]:/tmp$ mkdir try2018/anotherone
[email protected]:/tmp$ ls -ald try2018
drwxrwxr-x 3 greys greys 4096 Nov 5 21:04 try2018

Все эти команды сработали без ошибок, и ls показывает, что у меня есть полные права доступа к каталогу try2018 — rwx для меня, rwx для моей группы и r-x для всех остальных (это я читаю фрагмент drwxrwxr-x в строке с try2018).

Теперь давайте уберём права на запись (и создание новых объектов) в каталоге try2018:

[email protected]:/tmp$ chmod a-w try2018
[email protected]:/tmp$ ls -ald try2018
dr-xr-xr-x 3 greys greys 4096 Nov 5 21:04 try2018

Теперь мои права к этому каталогу сменились с полных (rwx — read/write/execute) на только чтение (r-x — read/execute).
Так что если я попробую создать в try2018 какой-то подкаталог, выйдет та самая ошибка про недостаток прав доступа:

[email protected]:/tmp$ mkdir try2018/yetanotherone
mkdir: cannot create directory 'try2018/yetanotherone': Permission denied

Чтобы исправить проблему, нужно исправить права доступа на каталоге, где мы видим ошибку. И пробуем mkdir снова:

[email protected]:/tmp$ chmod a+w try2018
[email protected]:/tmp$ mkdir try2018/yetanotherone

Вот теперь — порядок, всё создалось,

[email protected]:/tmp$ ls -ald try2018/yetanotherone
drwxrwxr-x 2 greys greys 4096 Nov 5 21:05 try2018/yetanotherone

На сегодня — всё! Будут ещё вопросы по самым основам Linux — обращайтесь!

The following code gives me the error : «mkdir : file exists».

    $path = 'c://wamp/www/et1/other';
    $new_location = 'c://wamp/www/et1/other/test';
    if(file_exists($path) && is_dir($path))
    {
        if(!file_exists($new_location))
        {               
            mkdir($new_location, 0777);
        }
    }

However, if I don’t put the second if condition, it gives me the error : «mkdir : no such file or directory». Also if I add recursivity by writting mkdir($new_location,077,true) I don’t get errors but the directory is not created. I just don’t understand what I could be doing wrong here.

asked Nov 5, 2012 at 14:56

Kestion's user avatar

KestionKestion

911 silver badge9 bronze badges

5

The error is caused by the double slashes in your paths, which PHP doesn’t like at all. If you change c:// to c:/ it will all work just fine.

And by the way, there’s no real reason to specify the 0777 as the mode because that’s also the default.

answered Nov 5, 2012 at 15:25

Jon's user avatar

JonJon

427k80 gold badges735 silver badges804 bronze badges

0

assuming that $new_location is the current path $path with a new directory name appended. you will need to mkdir with the recursive flag set to true, so that it Allows the creation of nested directories specified in the pathname.

http://php.net/manual/en/function.mkdir.php

mkdir($new_location, 0777, true);

answered Nov 5, 2012 at 15:05

Pedro del Sol's user avatar

Pedro del SolPedro del Sol

2,8309 gold badges39 silver badges52 bronze badges

2

The error is self explanatory

Warning: mkdir() [function.mkdir]: No such file or directory in

It means that the parent directory does not exist .. you need to add recursive option to create parent directory then the current directory

  mkdir($new_location, 0777, true);

If you don’t want to do that always check if parent directory exist

if (!is_dir(dirname($new_location)) || !is_writable(dirname($new_location)))
{
    trigger_error("Your parent does not exist");
}

answered Nov 5, 2012 at 15:07

Baba's user avatar

BabaBaba

93.7k28 gold badges166 silver badges217 bronze badges

Понравилась статья? Поделить с друзьями:
  • Mk10 ошибка при запуске приложения 0xc0000906
  • Mk10 ошибка 0xc000007b
  • Mk10 exe системная ошибка msvcp110 dll
  • Mk10 exe ошибка приложения 0xc0000906
  • Mk 11 ошибка game data is corrupted