Is using the include function in PHP secure for file inclusion, or are there potential risks involved?

Using the include function in PHP for file inclusion can be secure if proper precautions are taken, such as validating user input and using absolute paths. However, there are potential risks involved, such as including files from untrusted sources or allowing user-controlled input to determine the file path. To mitigate these risks, it is recommended to use the realpath function to resolve the file path to an absolute path before including it. This helps prevent directory traversal attacks and ensures that only files from the intended directory are included.

$filename = realpath($_GET['file']);
if ($filename !== false && strpos($filename, '/path/to/allowed/directory/') === 0) {
    include $filename;
} else {
    echo "Invalid file path";
}