What are some best practices for handling directory functions in PHP?

When working with directories in PHP, it is important to follow best practices to ensure proper handling and avoid errors. One common issue is not checking if a directory exists before performing operations on it. To solve this, you can use the `is_dir()` function to check if a directory exists before proceeding with any actions.

// Check if directory exists before performing operations
$directory = '/path/to/directory';

if (is_dir($directory)) {
    // Directory exists, proceed with operations
    // For example, list all files in the directory
    $files = scandir($directory);
    
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Directory does not exist.";
}