1

I'm making a PHP error page and I was wondering if there would be any way I could get the error code that resulted in the error and display it. Then, I could just use the same but have PHP display a different error code depending on what error happened. I am using Apache 2.4 with PHP 5.6.10. Any help would be greatly appreciated.

1 Answer 1

1

Point all error pages to one location in .htaccess

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php

Then in error.php you can do like this:

<?php
$status = $_SERVER['REDIRECT_STATUS'];
$codes = array(
       403 => array('403 Forbidden', 'The server has refused to fulfill your request.'),
       404 => array('404 Not Found', 'The document/file requested was not found on this server.'),
       405 => array('405 Method Not Allowed', 'The method specified in the Request-Line is not allowed for the specified resource.'),
       408 => array('408 Request Timeout', 'Your browser failed to send a request in the time allowed by the server.'),
       500 => array('500 Internal Server Error', 'The request was unsuccessful due to an unexpected condition encountered by the server.'),
       502 => array('502 Bad Gateway', 'The server received an invalid response from the upstream server while trying to fulfill the request.'),
       504 => array('504 Gateway Timeout', 'The upstream server failed to send a request in the time allowed by the server.'),
);

$title = $codes[$status][0];
$message = $codes[$status][1];
if ($title == false || strlen($status) != 3) {
       $message = 'Please supply a valid status code.';
}
// Insert headers here
echo '<h1>'.$title.'</h1>
<p>'.$message.'</p>';
// Insert footer here

From https://css-tricks.com/snippets/php/error-page-to-handle-all-errors/

--

If you would like custom error message for ex. parse error, you can add this to the top your PHP file:

<?php
set_error_handler('errorHandler');
function errorHandler($code, $msg, $file, $line) {

    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    echo "<h1>Unexpected error occurred</h1><p>The request was unsuccessful due to an unexpected error.</p>";
    // PHP error message:
    echo "<p>$msg</p>";
    die();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.