What best practices should be followed when selecting and displaying random images from a directory in PHP to avoid errors and optimize performance?

When selecting and displaying random images from a directory in PHP, it is important to ensure that the directory exists and contains images. Additionally, you should handle any potential errors that may occur during the selection process. To optimize performance, you can use functions like scandir() to get a list of files in the directory and array_rand() to select a random image.

// Specify the directory path
$directory = 'path/to/directory';

// Check if the directory exists
if (is_dir($directory)) {
    // Get a list of files in the directory
    $files = array_diff(scandir($directory), array('..', '.'));
    
    // Select a random image
    $randomImage = $files[array_rand($files)];
    
    // Display the random image
    echo '<img src="' . $directory . '/' . $randomImage . '" alt="Random Image">';
} else {
    echo 'Directory does not exist.';
}