如果有警告消息,请显示不同的内容

I have a little problem with a PHP warning:

I basically want to change the content of my page by clicking on links, like this:

<?php $page = ((!empty($_GET['page'])) ? $_GET['page'] : 'home'); ?>
<h1>Pages:</h1>
<ul>
    <li><a href="index.php?page=news">News</a></li>
    <li><a href="index.php?page=faq">F.A.Q.</a></li>
    <li><a href="index.php?page=contact">Contact</a></li>
</ul>
<?php include("$page.html");?>

This works really fine, but when I use a page that doesn't exist, for example localhost/dir/index.php?page=notapage i get following error:

Warning: include(notapage.html): failed to open stream: No such file or directory in
C:\xampp\htdocs\dir\index.php on line 8

Warning: include(): Failed opening 'notapage.html' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\dir\index.php on line 8

Is it possible to replace this warning by a custom message? (like a "404 not found")

Thanks in advance and happy easter!

You can do

if (file_exists($page.html)) {
include("$page.html");
}
else
{
echo "404 Message";
}

Source: PHP Manual

You can check if the file exists() and then include a custom 404 template.

<?php 
if (file_exists($page + '.html')) { 
    include ($page + '.html') 
} else { 
    include ('404.html'); 
}
?>

The idea is to check if the file exists before trying to include() it:

if(!file_exists("$page.html"))
{
    display_error404();
    exit;
}

include("$page.html");

Yes it is possible, though I would recommend sending a 404 unless you are going to also use clean url's (like /news, /faq, /contact) that redirect behind the scenes to the index.php, writing the page parameter. This is because index.php really does exist, you just have a bad parameter. Thus a 404 would not be appropriate. This is not to mention that you actually can;t set a 404 header in this location anyway since you have already sent output to the browser.

For you case just set up a conditional on whether the file_exists and is readable like this:

$include_file = $page . '.html';
if (file_exists($include_file) && is_readable($include_file)) {
   include($include_file);
} else {
   // show error message
}

You could use file_exists() but keep in mind that your approach is not very safe. A safer approach would be using an array with allowed pages. This way you have a better control over user input. Something like this:

$pages = array(
    'news' => 'News',
    'faq' => 'F.A.Q.',
    'contact' => 'Contact'
);

if (!empty($pages[$_GET['page']])) {
    include($_GET['page'].'html');
} else {
    include('error404.html');
}

You could also generate the menu using that array.