如何使 PHP 文件中的 .htaccess 显示错误?我的意思是当我搜索一个不存在的文件时,.htaccess 应该会显示一个来自 error.php 的错误页面,但是 error.php 需要一个带有错误代码的参数。
注意: .htaccess 应该直接在当前 url 上显示错误,而不需要重定向。我可以这样做还是不可能?还有其他方法吗?
如何使 PHP 文件中的 .htaccess 显示错误?我的意思是当我搜索一个不存在的文件时,.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
当您在 .htacess 中引用错误页面时,您所做的只是重定向:
ErrorDocument 404 /404.htm
将其更改为error.php?code=404
然后error.php
使用:
if($_GET['code'] == '404') {
include('404.php');
}
瞧!