You could just copy the Apache error documents into your web root (or symlink them in) and use header()
to set the error codes and with those documents as output. That's probably best unless you have a compelling reason not to. But in case that won't work for you, there are some alternatives (albeit, hacky alternatives).
For 500, just put a bug in your code.
<?php throw new Exception('Nooooooooooooooo!'); ?>
The PHP script will raise an exception, resulting in a regular Apache 500 error page. (But be aware of the caveat that this will only result in an Apache error if the PHP init setting display_errors
is set to 0
. In most development configurations, this is not the case. In most production configurations, this is the case. If you don't know your production server's setting, you'll have to just test this to see if it works.)
For 404, I think the best you can do is redirect to a non-existent page. It's not exactly the same thing, but might do for your purposes.
<?php header("Location: /i-dont-think-therefore-i-am-not"); ?>
In most browsers, the users won't actually see the redirect, they will just get silently and quickly redirected to a non-existent page, resulting in a regular Apache 404 error. Of course, the url will have changed and some users might notice that. If that's not acceptable, you can perhaps achieve similar results using Apache mod_rewrite to rewrite the url backend to a non-existent location.
To respond to several comments: Setting the response code via header()
(or some other way) will not result in the standard Apache error document. It will simply return that response code with your own output. This is intentional behavior, designed so that you can have custom error documents, or otherwise set response codes as the HTTP spec dictates on any request. If you want the Apache error documents, you have to either forge them (as per my initial suggestion of simply copying the error documents to your web root), or you'll have to trick Apache into returning them (as per my backup suggestion).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…