What are common pitfalls when using PHP to delete directories and how can they be avoided?

Common pitfalls when using PHP to delete directories include not checking if the directory exists before attempting to delete it, not handling permissions properly, and not recursively deleting all files and subdirectories within the directory. To avoid these pitfalls, always check if the directory exists before attempting to delete it, set the correct permissions on the directory and its contents, and recursively delete all files and subdirectories within the directory.

```php
function deleteDirectory($dir) {
    if (is_dir($dir)) {
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? deleteDirectory("$dir/$file") : unlink("$dir/$file");
        }
        rmdir($dir);
    }
}
```
This PHP function recursively deletes all files and subdirectories within the specified directory and then deletes the directory itself.