2013-03-29 37 views
0

我有一个PHP警告一个小问题:显示不同势内容,如果有一个警告信息

我基本上要通过点击链接,这样来改变我的网页的内容:

<?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");?> 

这个作品真的很好,但是当我使用的页面不存在,例如 localhost/dir/index.php?page=notapage我收到以下错误:

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 

是否有可能取代此警告是由自定义消息? (如“404找不到”)

在此先感谢和快乐的复活节!

回答

1

你可以做

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

来源:PHP Manual

+0

非常感谢!这正是我正在寻找的:) – muffin

0

您可以检查file exists()是否包含自定义404模板。

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

的想法是),以检查文件是否尝试包括(之前存在的话:

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

include("$page.html"); 
0

是它是可能的,但我会建议发送一个404,除非你要使用干净的网址(如/ news,/ f aq,/ contact),将后台重定向到index.php,编写页面参数。这是因为index.php确实存在,你只是有一个不好的参数。因此404不适合。这并不是说你实际上可以在这个位置设置一个404头文件,因为你已经发送了输出到浏览器。

对于你的情况下只设置了一个条件上是否file_exists并且是可读这样的:

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

你可以使用file_exists()但请记住,你的做法是不是很安全。 更安全的方法是使用带有允许页面的数组。这样您可以更好地控制用户输入。类似这样的:

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

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

您也可以使用该数组生成菜单。

+0

白名单是一个好主意。它会阻止某人要求导致安全问题的网页。 – Jocelyn

+0

这是非常真实的。 +1 –