Warning: mkdir(): File exists

Warning: mkdir(): File exists

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Warning: mkdir(): File exists

You are encountering a Warning: mkdir(): File exists error because your code attempts to create a subdirectory that already exists in the filesystem. In your current implementation, you generate a directory name using substr(uniqid(), -7) and then immediately call mkdir($path, 0700) inside the file processing loop.

The core issue is a mismatch between how you generate unique identifiers for directories versus files. You are creating a new subdirectory for every uploaded file, even if only one file is being processed in that request cycle. If the script runs twice in quick succession, or if your logic inadvertently re-enters the upload handler, uniqid() might return the same timestamp-based string, causing the second attempt to hit an existing folder.

However, a more common scenario with this specific pattern is that you are trying to create the directory inside a loop where it should only be created once per batch or per user session. If $path resolves to the same string for two different files in the same request (perhaps due to caching or logic reuse), mkdir() will fail on the second iteration because the first one succeeded.

Directory Persistence and Race Conditions

The mkdir() function returns false if the directory already exists by default. PHP does not automatically overwrite existing directories; that would be dangerous and could lead to data loss. To suppress the warning, you might be tempted to add | true to the end of the line or catch the exception, but this is a band-aid solution that hides a structural flaw.

The real fix involves ensuring the directory exists before attempting to move files. Instead of blindly calling mkdir(), use is_dir() to check if the path is already present. If it doesn't exist, create it. This approach handles both single-file uploads and batch uploads gracefully:

if (!is_dir($path)) {
    mkdir($path, 0700, true); // Create recursively with permissions
}

The third argument to mkdir() (true) is crucial here. It tells PHP to create any missing parent directories if they do not exist. Without this flag, a call like mkdir("uploads/2023/subfolder") will fail if 2023 isn't there yet. While your code generates the top-level directory name dynamically, ensuring recursive creation prevents errors if the script is run multiple times in a single minute.

Refactoring the Upload Logic

Looking at your loop structure, you are iterating over $_FILES['files']['name']. If a user uploads three images, you want one unique subdirectory to contain all three, not three separate directories named by three different uniqid() snapshots. Currently, your code generates a new $dir variable outside the loop but then ignores it if you were to move that line inside.

Wait, looking closely at your snippet:

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

You generate $dir once before the loop. This is actually correct for batch uploads if uniqid() produces a unique string every time. However, uniqid() relies on the current process ID and time. In high-load environments or under heavy CPU load, two uniqid() calls can theoretically return the same value within the same second.

A safer approach for directory naming in this context is to include a random component or use a hash of the request ID, but more importantly, you must ensure that mkdir is only called when necessary.

Here is the corrected logic block:

// Generate directory once per batch
$dir = substr(uniqid(), -7); 
$path = "uploads/$dir/"; 

// Ensure directory exists before processing files
if (!is_dir($path)) {
    mkdir($path, 0755, true); // Use 0755 for web servers unless strict security is needed
}

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

        if ($_FILES['files']['error'][$f] == 0) {
            // Validation logic...
            
            $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)) {
                // Success logic
            }
        }
    }
}

Security and Permissions Considerations

While fixing the error, consider your permissions. You are setting 0700 for the directory. This restricts access to the owner only. If your web server runs as a user different from your application (common in shared hosting or containerized environments), this write permission might block future uploads if the file is moved back or if the script needs to clean up later.

Standard practice for upload directories is 0755 (read/execute for others, read/write/execute for owner) or 0775 in groups where applicable. However, if you are storing sensitive data, 0700 might be intentional, provided the web server user owns the directory. Always verify the owner of the uploaded file after moving it; by default, move_uploaded_file preserves the ownership of the temporary upload, which is usually the web server user, not your application user.

If you are building a production system where data integrity and security are paramount, consider using Laravel's filesystem manager or similar abstractions that handle directory existence checks and atomic movements internally. For example, Laravel provides robust file handling utilities that abstract away these low-level mkdir and move_uploaded_file calls, reducing the risk of race conditions and permission errors [[https://laravelcompany.com]].

In summary, the warning appears because your application assumes a directory is never present. By checking with is_dir() and creating it only when missing, you align your code with how the operating system actually manages filesystem state.

Our network