What are some best practices for using the include() function in PHP to prevent security vulnerabilities?

When using the include() function in PHP, it is important to sanitize user input to prevent directory traversal attacks and other security vulnerabilities. One way to do this is by using a whitelist approach, where you only allow specific files to be included. Another best practice is to use absolute file paths instead of relative paths to ensure that the included files are located in the expected directories.

// Whitelist approach to include only specific files
$allowed_files = ['file1.php', 'file2.php', 'file3.php'];
$file_to_include = $_GET['file'];

if (in_array($file_to_include, $allowed_files)) {
    include($file_to_include);
} else {
    // Handle error or redirect to a safe location
}