Custom Error Pages Using PHP & .htaccess

Started by RyanJones, February 26, 2006, 07:52:57 AM

Previous topic - Next topic

RyanJones

Something I wrote for my host a host go, someone here may find it useful.

Introduction:
Hi everyone and in this tutorial we will talk about how you can make those professional looking custom error pages that most paid sites use!

Your probably saying to your self... this is going to be hard - I know nothing about PHP but this does not matter only a small amount of PHP is required and I will explain anything you do not understand.

Most paid hosts do not have features like this amd luckily for us (And a big thanks to Mike) we have the ability to use both the rquired components, htaccess and PHP.


Information About .htaccess?
A .htaccess file is a simple ASCII file, such as you would create through a text editor like NotePad or SimpleText. Many people seem to have some confusion over the naming convention for the file, so let me get that out of the way.

.htaccess is the file extension. It is not file.htaccess or somepage.htaccess, it is simply named .htaccess.
Most commands in htaccess are meant to be placed on one line only, so if you use a text editor that uses word-wrap, make sure it is disabled or it might throw in a few characters that annoy Apache to no end, although Apache is typically very forgiving of malformed content in an htaccess file.

.htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.somehost.com) would affect yoursite.somehost.com/content, yoursite.somehost.com/content/contents, etc. It is important to note that this can be prevented (If, for example, you did not want certain .htaccess commands to affect a specific directory) by placing a new .htaccess file within the directory you don't want affected with certain changes, and removing the specific command(s) from the new .htaccess file that you do not want affecting this directory. In short, the nearest .htaccess file to the current directory is treated as the .htaccess file. If the nearest .htaccess file is your global .htaccess located in your root, then it affects every single directory in your entire site.


Looking at your current .htaccess file:
Now the introduction is over lets have a look at the contents of the current .htaccess file you should have in your cpanel.

First log into CPanel and then click "File Managere" Once there click the  yellow folder icon by the folder named "public_html". In this folder (The root folder for everything to be displayed publically on the server) you could see a few folders names with underscores at the start and a .htaccess file. Click the .htaccess file's name and then on the left hand side (top) of your screen you should see a few options, click the "Edit File" option. This should not load the contents of the document into a new window with a textbox in it.

Before we go any further I must state they you should NEVER remove the existing content of this file... Everything currently in there has a reason for being so and should not be removed or edited.

The htaccess command we will be looking at is called ErrorDocument.

This command has the following syntax:
ErrorDocument Error_Number Redirect_Location


Command Description:
This function acepts two arguments, the first is the error number to be processes, for example a 404 (Page Not Found Error).
The second is the page to redirect too (We will use this later.)


An example:
ErrorDocument 400 http://www.simplemachines.org/Error=400

This would redirect a 400 error (Server cannot process a request) to a page called Error.php (Anything after that will be discussed later on in this tutorial.)


Onto the next stage: Using PHP to process the information...
As you can see the command is pretty simple to use and understand but now we move on to the next section, the use of PHP to display information reguarding the error.

First, add the following line to your open .htaccess file (At the end):

ErrorDocument 404 http://{Your_Domain_Name_Here}/Error.php?Error=404

Change {Your_Domain_Name_Here} to your location (Including extension) on the HHH server.

This redirects the most common error, a page not found error. Save this file.

Next you will need to create a new file in in your root "public_html" folder called Error.php.

Then open this file for editing and paste in the following:

<?php
 
if (isset($_GET['Error']))
 {
   
$Error = $_GET['Error'];
 }
 else
 {
   
header('Location: index.php');
 }
 
$Text = '';
 
$Do_What = '';
 switch(
$Error)
 {
   case
404:
     
$Text    = 'A <span class="Error" style="font-style:italic;">404</span> error has occured. This means the file/folder you requested does not exist.';
     
$Do_What = 'Please try typing the file/folder name again and or, check the file still exists.';
      break;
 }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style type="text/css">
      <!--
        body
        {
          background-color: #202831;
        }
        .Error
         {
          color: #FF0000;
          font-weight: bold;
        }
      //-->
    </style>
    <title>ERROR!</title>
  </head>
  <body>
    <font size="1">
    <?php
     
echo '<span class="Error">An Error has occured.</span><br /><br />';
     echo
'<span class="Error">Error:</span> ' . $Text . '<br /><br />';
     echo
'<span class="Error">What can I do:</span> ' . $Do_What . '<br />';
   
?>
    </font>
  </body>
</html>


Now, save the file and then type in a location that does not exist in your site, for example: http://{Your_Domain_Name_Here}/foo/page_1.php (Or, try mine: http://www.standards.spiralmindsinc.com/foo/page_1.php for example.)

And you should be redirected to the Error.php page with a message.

Before we go into customising your version I had better provide a description of the PHP parts.

PHP Part Description:
As you can see the code above is a little bit more complicated than the code we used earlier and so, it will need a little more explination.

First part:

<?php
 
if (isset($_GET['Error']))
 {
   
$Error = $_GET['Error'];
 }
 else
 {
   
header('Location: index.php');
 }

?>


This grabs the error perameter given to a HTML page, is one if not sent then we do not have an error so redirect them to index.php.

Second part:
<?php
$Text
= '';
$Do_What = '';
?>


Declare the variables we will be using to store the error data.

Third and final part:
<?php
 
switch($Error)
 {
   case
404:
     
$Text = 'A <span class="Error" style="font-style:italic;">404</span> error has occured. This means the file/folder you requested does not exist.';
     
$Do_What = 'Please try typing the file/folder name again and or, check the file still exists.';
   break;
 }
?>


This is used when selecting multiple errors, in this case if a 404 error perameter was passed (case 404) then set the pre-defined varibles to the needed information ready to be printed to the page later.

Forth part; the display:

<?php
 
echo '<span class="Error">An Error has occured.</span><br /><br />';
 echo
'<span class="Error">Error:</span> ' . $Text . '<br /><br />';
 echo
'<span class="Error">What can I do:</span> ' . $Do_What . '<br />';
?>


Writed the error to the document.


Customizing your error page....

To add more error pages all you have to do is add another case to the select statement like so:

<?php
 
switch($Error)
 {
   case
404:
     
$Text = 'A <span class="Error" style="font-style:italic;">404</span> error has occured. This means the file/folder you requested does not exist.';
     
$Do_What = 'Please try typing the file/folder name again and or, check the file still exists.';
   break;

   case
400:
     
$Text = 'A <span class="Error" style="font-style:italic;">400</span> the server could not process your requested action.';
     
$Do_What = 'Please try again later.';
   break;
}
?>



So, by adding a new case statement we have a whole new reult.

I you really wanted you could change this competly to use images and make an entire page that is customized to anything; even alerting the administrator of the error!

Cheers,

Ryan Jones
RyanJ (Ryan Jones)

Support Web Standards!

Currently working On: Additions to the Karma system.

H

I was thinking about using PHP for my error pages. The problem is I can't get all the error information I can just using Apache shtml.

My current 404 page (I haven't made it pretty yet) is:


<html>
<head>
<meta name="robots" content="noindex,nofollow">
<title>Huw.org.uk - Error</title>
</head>
<body>
<h1>An Error has occurred</h1>
<p>Information for administrators:
<ul>
<li>Referer: <!--#echo var="HTTP_REFERER" -->
<li>Requested Page:<!--#echo var="REQUEST_URI" -->
<li>Domain: <!--#echo var="HTTP_HOST" -->
<li>Error: <!--#echo var="REDIRECT_STATUS" -->
</ul>
</p>
</body>
</html>


Is it possible to get all the same information using PHP?
-H
Former Support Team Lead
                              I recommend:
Namecheap (domains)
Fastmail (e-mail)
Linode (VPS)
                             

RyanJones

Those exact same vars are available from the $_SERVER global variable in PHP.

There are some problems with some e.g. HTTP_REFERER and REQUEST_URI because in the act of redircting theapahe changed the values...

I'm looking into ways of using the perl $ENV var in he .htaccess file to put them in the URL for pharseing.

Cheers,

Ryan Jones
RyanJ (Ryan Jones)

Support Web Standards!

Currently working On: Additions to the Karma system.

H

Looks like I will have to try a PHP error page again.

One question :P. What is the PHP env. variable of <!--#echo var="REDIRECT_STATUS" -->
-H
Former Support Team Lead
                              I recommend:
Namecheap (domains)
Fastmail (e-mail)
Linode (VPS)
                             

RyanJones

Quote from: huwnet on February 27, 2006, 04:04:08 PM
Looks like I will have to try a PHP error page again.

One question :P. What is the PHP env. variable of <!--#echo var="REDIRECT_STATUS" -->

$_SERVER['REDIRECT_STATUS'] as far as I know.

http://uk.php.net/reserved.variables

Cheers,

Ryan Jones
RyanJ (Ryan Jones)

Support Web Standards!

Currently working On: Additions to the Karma system.

H

Ah, thanks I obviously didn't look very well ::)
-H
Former Support Team Lead
                              I recommend:
Namecheap (domains)
Fastmail (e-mail)
Linode (VPS)
                             

RyanJones

Quote from: huwnet on February 28, 2006, 11:35:11 AM
Ah, thanks I obviously didn't look very well ::)

You can use print_r($_SERVER); to see if it has anyting else you like :)

Cheers,

Ryan Jones
RyanJ (Ryan Jones)

Support Web Standards!

Currently working On: Additions to the Karma system.

Parham


Advertisement: