从PHP文件显示404错误页面,无需重定向

vee*_*oor 5 php http-status-code-404

我有一个文件secret.php包含在内index.php,我想在有人试图secret.php直接访问时显示404错误页面.但

header("Location: this_site_certainly_does_not_exist");
Run Code Online (Sandbox Code Playgroud)

in secure.php不是解决方案,因为我希望在example.com/secret.php显示错误页面时,用户键入的URL(例如)在浏览器的URL栏中可见,而不是重定向.

aks*_*ksu 11

你可以用标题来做.

header("HTTP/1.0 404 Not Found");
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用示例readfile方法添加404页面.

header("HTTP/1.0 404 Not Found");
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();
Run Code Online (Sandbox Code Playgroud)


小智 0

我不明白为什么你想将其保留在浏览器中,最佳实践是将用户重定向到 404 页面。

我建议使用 apache (.htaccess) 或 nginx 重定向来完成此操作。