In what situations should one consider checking if a PHP file exists before including it?

It is important to check if a PHP file exists before including it to prevent errors or security vulnerabilities. This is especially crucial when including user input or dynamically generated file paths. By checking if the file exists, you can avoid including non-existent files and potentially exposing sensitive information or executing malicious code.

$file_path = 'path/to/file.php';

if (file_exists($file_path)) {
    include $file_path;
} else {
    // handle the case where the file does not exist
    echo 'File does not exist.';
}