如何使.htaccess显示PHP文件中的错误?我的意思是,当我搜索一个不存在的文件时,htaccess应该显示error.php中的错误页面,但error.php需要一个带有错误代码的参数。
注意:.htaccess应直接在当前url上显示错误,而无需重定向。我能这样做吗?还是不可能?还有其他办法吗?
您正在寻找ErrorDocument
。
在.htaccess中指定要处理的代码,如:
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php
在error.php中,处理错误代码,如:
<?php
$code = $_SERVER['REDIRECT_STATUS'];
$codes = array(
403 => 'Forbidden',
404 => 'Not Found',
500 => 'Internal Server Error'
);
$source_url = 'http'.((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 's' : '').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (array_key_exists($code, $codes) && is_numeric($code)) {
die("Error $code: {$codes[$code]}");
} else {
die('Unknown error');
}
?>
//Custom 403 errors
ErrorDocument 403 your-path/403.php
//Custom 404 errors
ErrorDocument 404 your-path/404.php
//Custom 500 errors
ErrorDocument 500 your-path/500.php
当您在.htaccess中引用错误页面时,您所做的只是重定向:
ErrorDocument 404 /404.htm
将其更改为error.php?code=404
,然后使用在error.php
中拾取
if($_GET['code'] == '404') {
include('404.php');
}
哇!