php-how to delete files from directory if files already exist?

php-how to delete files from directory if files already exist?

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

Stefan Bogdanescu

Founder & Senior Architect

The Critical Mistake in Your File Deletion Logic

The core issue preventing your file upload logic from working lies in how unlink() interacts with directory paths versus individual files. In your current implementation, you define $path_user as a directory path (ending with a trailing slash) and then attempt to call unlink($path_user). The unlink() function is designed exclusively for removing files. When you pass it a directory path, PHP returns false and does not delete the directory or its contents because directories require rmdir() for deletion, and even that only works if the directory is empty.

This logic error occurs right after your conditional block that creates the directory using mkdir(). If the directory creation succeeds, $path_user now points to an existing folder. The subsequent line tries to delete that folder as if it were a file. Since the operation fails silently (or throws a warning depending on error reporting levels), execution continues immediately to move_uploaded_file(). This results in PHP attempting to move the uploaded file into a directory that might already contain files from previous uploads, or failing entirely because the intended "fresh start" logic never executed.

To fix this, you must ensure that if a target directory exists, it is removed before attempting to create it again or before moving the new file in. However, blindly removing a directory can be dangerous. You need to verify exactly what exists at that path and handle the cleanup strategically.

Handling Directories vs. Files Correctly

In your specific scenario, you are trying to enforce a single-file-per-ID structure within /wp-content/plugins/est_collaboration/Files/{send_id}/. If this directory already exists, it likely contains an old file corresponding to that $send_id. You cannot use unlink on the directory path itself.

If your goal is to reset the storage for a specific user or session ID, you should check if the directory exists. If it does, and you intend to overwrite the existing content, you have two primary approaches:

  1. Delete the Directory: Use rmdir() only if you are certain the directory is empty. Since your code creates an empty directory first, checking for emptiness before deletion is safer.
  2. Use a Recursive Deletion Utility: For production environments where the directory might contain multiple files (e.g., thumbnails or cache), use a recursive deletion function.

Here is a corrected approach that safely handles the existence check:

$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';

// Check if the directory exists first
if (is_dir($path_user)) {
    // Attempt to remove the entire directory and its contents safely
    $success = rmdir($path_user); 
    
    // If rmdir fails because the dir isn't empty, you need a recursive delete
    if (!$success) {
        $iterator = new RecursiveDirectoryIterator($path_user);
        $recursiveIterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST);
        
        foreach ($recursiveIterator as $file) {
            if ($file->isDir()) {
                rmdir($file->getPathname());
            } else {
                unlink($file->getPathname());
            }
        }
        // Now try to remove the now-empty directory again
        if (!rmdir($path_user)) {
            throw new Exception("Failed to delete existing directory: $path_user");
        }
    }
}

// Only create the directory if it didn't exist previously
if (!is_dir($path_user) && !mkdir($path_user, 0777, true)) {
    throw new Exception("Failed to create directory: $path_user");
}

// Now move the uploaded file safely
$path_final = $path_user . $path;

if (move_uploaded_file($file['tmp_name'], $path_final)) {
    echo "Your File Successfully Uploaded";
} else {
    throw new Exception("Failed to move uploaded file.");
}

Security and Permission Considerations

While the logic above resolves the immediate functional error, relying on 0777 permissions for a directory in /wp-content/ is a significant security risk. This permission setting allows any user with write access to the filesystem to read, write, or execute files within that directory. In a shared hosting environment or a production server, this opens your application to arbitrary file uploads and potential remote code execution attacks.

You should restrict permissions based on your operating system's capabilities:

  • Linux/Unix: Use 0755 for directories (read/execute for all, read/write/execute for owner) and ensure the web server user owns the directory.
  • Windows: Adjust NTFS ACLs to match application needs without granting full world-write access.

If you are using a framework like Laravel, consider delegating file storage logic to the Storage facade, which handles these permissions and path abstractions more securely out of the box. For instance, utilizing the Storage::makeDirectory() and deleteDirectory() methods provides a cleaner API than raw mkdir and rmdir calls, reducing the chance of permission-related bugs.

Conclusion

The failure in your original code stemmed from attempting to delete a directory path using unlink(). By switching to rmdir() or a recursive deletion strategy, verifying directory existence, and tightening file permissions, you can ensure that each upload operation starts with a clean slate without compromising system integrity.

Our network