【问题标题】:Throw 404 Not Found from PHP抛出 404 未从 PHP 中找到
【发布时间】:2014-12-29 08:59:12
【问题描述】:

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

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

我该如何处理这个网址?

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

【问题讨论】:

  • 试试这个header("HTTP/1.0 404 Not Found")

标签: php .htaccess error-handling


【解决方案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错误页面

【讨论】:

  • 有什么方法可以重定向到我的 404.php 页面吗?重定向发送 404 标头?
  • @mauriblint 您可以重定向到 404 页面并将 404 Not Found 标头放在那里:我已经用这个替代方法更新了我的答案
【解决方案2】:

PHP &gt;= 5.4.0 开始,您可以使用http_response_code function

if ($notExistDB) {
   http_response_code(404);
   exit;
}

【讨论】:

  • 我的 PHP 5.3 中的未定义函数,还有其他方式吗?
  • 嗯,对于 PHP 5.3,您将不得不使用 Header 函数,请参阅其他答案。
猜你喜欢
  • 2013-02-07
  • 2018-09-19
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多