从PHP找不到404

时间:2014-11-02 16:46:49

标签: php .htaccess error-handling

如何从php中抛出错误代码404? 在我的htaccess中,我有一个规则,将标签重定向到类别,但如果在搜索数据库中的类别后,如果不存在,我该如何重定向到404错误页面并发送正确的标题?

RewriteRule ^([a-z]{2})/(.*)$ index.php?lang=$1&id=$2 [L]

我该如何处理这个网址?

site.com/en/this-category-not-exists

2 个答案:

答案 0 :(得分:1)

如果记录不存在,您可以使用以下代码:

<?php
header("HTTP/1.0 404 Not Found");
echo 'This page was not found';
?>

如果您想使用外部404错误页面,可以改为使用:

<?php
header("HTTP/1.0 404 Not Found");
include("404errorpage.php");
?>

或者,您可以使用

重定向到404错误页面
header("Location: http://example.com/404errorpage.php");

但是你必须把

header("HTTP/1.0 404 Not Found");

进入404错误页面

答案 1 :(得分:1)

PHP >= 5.4.0开始,您可以使用http_response_code function

if ($notExistDB) {
   http_response_code(404);
   exit;
}
相关问题