What are the best practices for securely implementing random file inclusion in PHP?

Random file inclusion in PHP can be a security risk if not implemented securely. To prevent potential attacks like directory traversal or remote file inclusion, it is important to validate user input and restrict the files that can be included. One approach is to use a whitelist of allowed files and sanitize user input before including any files.

$allowed_files = ['file1.php', 'file2.php', 'file3.php'];

if (isset($_GET['file']) && in_array($_GET['file'], $allowed_files)) {
    include $_GET['file'];
} else {
    // Handle error or default behavior
}