What potential pitfalls should beginners be aware of when trying to display directory contents in a browser with PHP?

Beginners should be aware of potential security risks when displaying directory contents in a browser with PHP, as it can expose sensitive information or allow unauthorized access to files. To mitigate these risks, it is important to properly sanitize and validate user input, restrict access to certain directories, and avoid displaying sensitive file information.

<?php
// Ensure the directory path is valid and restrict access to specific directories
$directory = 'path/to/directory';
$allowed_directories = ['public', 'uploads'];

if (in_array($directory, $allowed_directories)) {
    // Display directory contents
    $files = scandir($directory);
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Access denied.";
}
?>