Show 404 error page from PHP file, without redirec

2019-05-04 19:04发布

问题:

I have a file secret.php which is included in index.php and I want to show a 404 error page when someone tries to access secret.php directly. But

header("Location: this_site_certainly_does_not_exist");

in secure.php is not a solution, because I want the URL the user typed (e.g. example.com/secret.php) to be visible in the browser's URL bar when the error page is shown, instead of redirecting.

回答1:

You can do it with headers.

header("HTTP/1.0 404 Not Found");

then you can add your 404 page using for example readfile method.

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();


回答2:

You need to send a html 404 status code to the client. You can achieve that with: http://www.php.net/manual/en/function.http-response-code.php



回答3:

I don't see why you would want to keep that in browser, best practice is to redirect the user to a 404 page.

I'd suggest to do it with an apache (.htaccess) or nginx redirect.



回答4:

I'm not sure about your application architecture, but Codeignter does this by including a common file that is used in all files (in their case index.php)

The index.php file includes a define

define('BASEPATH', $system_folder.'/');

And then in files that should only be used by being included in other files

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

See how you can adopt that scheme for your own situation.



回答5:

for permanent solution you can use .htaccess for redirecting when secret.php is called

  # Mod for redirecting specific URL requests to a custom error page
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} ^/secret.php [NC]
  RewriteRule . /your-error-page.php [L]
  # End of custom mod