What are the potential pitfalls of including external files in PHP scripts, and how can developers ensure proper file inclusion without compromising security or causing errors?

Potential pitfalls of including external files in PHP scripts include security vulnerabilities such as file inclusion attacks and errors due to incorrect file paths or missing files. To ensure proper file inclusion without compromising security or causing errors, developers should sanitize user input, validate file paths, and use absolute paths instead of relative paths.

// Example of including external file with proper validation and absolute path
$allowed_files = ['file1.php', 'file2.php'];
$file_to_include = $_GET['file'];

if (in_array($file_to_include, $allowed_files)) {
    include_once(__DIR__ . '/' . $file_to_include);
} else {
    echo 'Invalid file included';
}