2

How can I make .htaccess display errors from a PHP file? I mean when I search a non-existing file .htaccess should show me an error page from error.php, but error.php needs a parameter with the error code.

NOTE: .htaccess should show the error directly on the current url without redirecting. Can I do this or it is impossible? Are there any other ways?

halfer
  • 19,824
  • 17
  • 99
  • 186
Roman Hudylko
  • 43
  • 1
  • 1
  • 6

3 Answers3

10

You're looking for ErrorDocument.

In your .htaccess specify the codes you want to handle, like:

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

And in error.php, handle the error codes like:

<?php
    $code = $_SERVER['REDIRECT_STATUS'];
    $codes = array(
        403 => 'Forbidden',
        404 => 'Not Found',
        500 => 'Internal Server Error'
    );
    $source_url = 'http'.((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 's' : '').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    if (array_key_exists($code, $codes) && is_numeric($code)) {
        die("Error $code: {$codes[$code]}");
    } else {
        die('Unknown error');
    }
?>
0x47686F7374
  • 434
  • 2
  • 14
1
//Custom 403 errors
ErrorDocument 403 your-path/403.php

//Custom 404 errors
ErrorDocument 404 your-path/404.php

//Custom 500 errors
ErrorDocument 500 your-path/500.php
Yatin Mistry
  • 1,246
  • 2
  • 13
  • 35
  • Please add an explanation of what the above has to do with the question asked. How does it relate to the requested `.htaccess` file? – War10ck Sep 16 '14 at 13:05
  • Sorry, but such approach redirect user on error to related php page, I need to display an error on the go. – Roman Hudylko Sep 16 '14 at 13:07
  • This *is* what you need. You can make these pages act exactly as you're asking - for eample they can all be symlinked to the same file which inspects the env vars (e.g. `$_SERVER`) to figure out which error to display. – Synchro Sep 16 '14 at 13:24
  • 1
    Wrong syntax. Relative paths are not allowed. The paths in your example should start with / – David Gausmann Apr 16 '21 at 08:32
0

When you reference an error page in .htacess, all your doing is a redirect:

ErrorDocument 404 /404.htm

Change that to error.php?code=404 and then pick that up in error.php using:

if($_GET['code'] == '404') {
    include('404.php');
}

Voila!

Edward
  • 1,806
  • 5
  • 26
  • 36
  • 1
    "all your doing is a redirect" - a "redirect" implies a 3xx external redirect - which this is not. When an `ErrorDocument` is triggered it is an "internal subrequest". You also don't need to explicitly pass the HTTP status code, since this is available in the `$_SERVER['REDIRECT_STATUS']` superglobal. – MrWhite Jan 06 '17 at 15:05