What is the recommended approach for handling directory creation in PHP to avoid potential pitfalls?

When creating directories in PHP, it is important to check if the directory already exists before attempting to create it. This helps avoid potential issues such as overwriting existing directories or encountering errors. To handle directory creation safely, you can use the `is_dir()` function to check if the directory exists and then create it only if it doesn't already exist.

$directory = 'path/to/directory';

if (!is_dir($directory)) {
    mkdir($directory, 0777, true);
    echo "Directory created successfully";
} else {
    echo "Directory already exists";
}