What best practices should be followed when displaying directory contents using PHP?

When displaying directory contents using PHP, it is important to follow best practices to ensure security and proper functionality. One key practice is to sanitize user input to prevent directory traversal attacks. Additionally, it is recommended to use functions like `scandir()` to retrieve directory contents and properly handle file paths to avoid errors.

$directory = 'path/to/directory';

// Sanitize user input
$directory = realpath($directory);

// Check if the directory exists
if (is_dir($directory)) {
    // Get directory contents
    $files = scandir($directory);

    // Display files
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Invalid directory";
}