Trigger 500 Internal Server Error in PHP and display Apache error page

After such a knowledge-full discussion, i think there is no php code can display the by default 500 Internal Server Error. The solution is :
1. Create a folder named http500 next to the php file.
2. Create a .htaccess file in it and add following code :

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^])(.(*/
    RewriteRule ^])((a-zA
</IfModule>
  1. PHP redirect code :

header('location : http500/');


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).


function ISE()
{
  header('HTTP/1.1 500 Internal Server Error', true, 500);
  trigger_error('ISE function called.', E_USER_ERROR);//if you are logging errors?
}

However, you will need output buffering ON to be able to use php header() function after you use any output function like echo.

Tags:

Php

Apache