【发布时间】:2014-07-25 14:25:40
【问题描述】:
为了包含正确的文件并在发生错误时显示错误页面,我有以下代码(非常简化):
$page = 'examplePage.php';
$page404 = '404.php';
if (file_exists($page))
{
require($page);
}
else if (file_exists($page404))
{
require($page404);
}
else
{
// Tell the browser to display his default page
}
?>
总结一下:
如果我有文件,我会包含它。
如果我没有该文件,我将包含错误文件。
如果错误文件也不存在怎么办?
我希望将其呈现为浏览器的默认错误页面。
我已经使用 Internet Explorer 通过发送带有 HTTP 错误的空内容来实现这一点。 问题是其他浏览器的行为不一样,它们都显示一个空白页面。
有没有办法告诉浏览器显示自己的错误页面? (不仅是 404,而是所有错误:304、500 等)
谢谢。
编辑:我忘了告诉你,我可以完全控制我发送的标题和响应发送的内容。
编辑 2: 这是一些代码
// possible paths to retrieve the file
$possiblePaths = array(
$urlPath,
D_ROOT.$urlPath,
D_PAGES.$urlPath.'.php',
D_PAGES.$urlPath.'/index.php',
$urlPath.'.php'
);
foreach ($possiblePaths as $possiblePath)
if (file_exists($possiblePath) && !is_dir($possiblePath))
{
if (!is_readable($possiblePath))
{
Response::setCode(403); // calls the header(403)
self::$filePath = self::getErrorPage(403);
}
else
self::$filePath = $possiblePath;
break;
}
if (self::$filePath === null) // no file found => 404
{
Response::setCode(404); // call the header(404)
self::$filePath = self::getErrorPage(404);
}
public static function _getErrorPage($code)
{
if (is_readable(D_ERRORS.$code.'.php')) // D_ERRORS is the error directory, it contains files like 404.php, 403.php etc
return D_ERRORS.$code.'.php';
else
{
/*-------------------------------------------------*/
/* Here i go if the error file is not found either */
/*-------------------------------------------------*/
if ($code >= 400)
Response::$dieResponse = true; // removes all output, only leaves the http header
return null;
}
}
?>
这是我打印内容的时候:
<?php
if (self::$dieResponse)
{
self::$headers = array(); // no more headers
self::$content = ''; // no more response
}
http_response_code(self::$code); // HTTP code
foreach (self::$headers as $key => $value)
header($key.': '.implode(';', $value)); // sends all headers
echo self::$content;
?>
编辑:这里有一些截图来解释我想要什么。
这是我在 IE 中得到的:
这正是我想要的。
现在,在所有其他浏览器中,我都有一个空白页。 我不想要空白页。
例如,我希望 Chrome 显示以下内容:
【问题讨论】:
-
如果您的错误页面本身丢失,您不会遇到比用户看到的更大的问题吗?
-
请注意:浏览器与 404(或任何其他)错误页面无关。这一切都在服务器上。如果在服务器上看到错误情况,它将查找 .htaccess 中 ErrorDocument 下列出的相关错误页面,然后查找自定义文档(例如 /404.shtml),最后使用它自己的默认页面。浏览器只显示服务器决定发送的任何内容。
-
ceejayoz :没问题,在这种情况下,它只是意味着我没有针对此错误显示的特定文件。菲尔佩里:对,但错了。服务器规则,但浏览器有默认错误页面。这也是为什么 404 页面在不同浏览器中看起来不一样的原因。 Fred-ii-:我不能使用 apache 指令。他可能 404 不是 404 的东西(如果我的服务器上不存在该文件,并不意味着没有要加载的文件)。
-
注意:不是所有的页面都是标准的浏览器,很多都是标准的服务器(例如 Apache、Nginx、lighttpd 等)
-
@GuilhermeNascimento 我不知道这个。如果你知道触发这些页面的方法,那我就全部打开了。