What are the best practices for handling file operations in PHP to avoid unintended consequences like folder duplication?

When performing file operations in PHP, it's crucial to check if the target directory already exists before attempting to create it to avoid unintended consequences like folder duplication. This can be achieved by using PHP's `file_exists()` function to check if the directory exists before creating it.

$directory = 'path/to/directory';

if (!file_exists($directory)) {
    mkdir($directory, 0777, true);
} else {
    // Directory already exists, handle accordingly
}