PHP also allows you to capture the errors and create your own custom error functions or pages.. Not only can you use PHP code to trap errors and customize the error messages, you can use
Trang 1It is of the utmost importance that you know how to handle your errors and debug your own code
Being able to efficiently and properly debug your code is an invaluable time saver, and in web development, $time == $money!
Luckily, PHP provides you with many ways to isolate and resolve most, if not all, of these unwanted errors PHP also allows you to capture the errors and create your own custom error functions or pages These features are useful when debugging your code and when notifying your webmaster about errors that seem to be happening to your applications as users are running them
Not only can you use PHP code to trap errors and customize the error messages, you can use the Apache web server to help do this
How the Apache Web Ser ver Deals
with Errors
Apache has a directive, the ErrorDocument , that you can configure in the httpd.conf file to create custom error pages with PHP, so visitors to your site do not see the default server - based error pages, which may not be as helpful or descriptive as customized error messages
You have limitless possibilities when creating these custom messages As with the PHP error catching pages, you can have the ErrorDocument call PHP pages to do whatever you would like them to do — from simply displaying a friendly error message to the user, to e - mailing a system administrator to notify him or her of the failure
Trang 2Unlike PHP error pages, the Apache ErrorDocument pages are used more for instances of missing pages
(that is, a Page Not Found error or Forbidden Access error pages and other requests of that sort) So,
if someone visits your site and runs into the Page Not Found error page, the script will e - mail the
administrator, who can in turn check to see whether this was a valid request and there is something
wrong with the page or server, or whether someone was just looking for the wrong pages, or if this was
a malicious user trying to sniff around where he or she wasn ’ t supposed to be
Apache ’ s ErrorDocument Directive
Error handling is an invaluable resource and a must have for web developers, to keep their sites up and
running with the fewest end - user problems or complaints If you rely solely on people contacting you to
tell you about errors on your site, it is difficult to have a smoothly running server Allowing the server
to do this for you will greatly increase your success at running a smooth server This section first looks at
Apache ’ s ErrorDocument method of error handling
First of all, you need to make some changes to the httpd.conf file to allow you to create a custom
error page Apache is usually set up by default to go to its own internal error pages, but you don ’ t
want that You want Apache to go to your custom error page, no matter what error has occurred
To do this, you change the default settings to your own specific settings by following these steps:
1 Open up your httpd.conf file, and you will find some lines that look like this:
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
Trang 3How It Works You have just edited Apache ’ s configuration file to help you with error handling By using the
ErrorDocument directive, you are able to send users to specific error pages, depending on what error the server has encountered For example, if you receive a 404 error, the typical “ Page Cannot Be Found ” page, you can redirect it to a page you have created to look like your web site, while still getting the message through to the user that there has been a problem You can do that with any and all error messages that the server can encounter
Many ErrorDocument codes exist, but we will focus on the error messages you see typically in everyday web browsing:
400: Bad Request 401: Authorization Required 403: Forbidden
404: Not Found 500: Internal Server Error
Numerous other error codes exist, of course You can find a complete list at http://rfc.net/
rfc2616.html#p57 Although you are seeing just a few error codes in this exercise, you can catch others as well by simply adding another ErrorDocument to the httpd.conf file For example, if you want to implement the 501 error code, you simply add ErrorDocument 501 /error.php?501 to your code and add the error handling in the error.php page, which you ’ ll see shortly
Next, you ’ ll see a simple way to show the user error messages, and then get into some more complex ways to notify the webmaster of errors occurring on the web site by using the mail() function, which you learned previously
To show the user error messages, follow these steps:
1 Open your text editor, and save a page called error.php
2 Enter the following code:
Trang 4echo ‘ < h1 > Bad Request < /h1 >
echo ‘ < h2 > Error Code 400 < /h2 >
echo ‘ < > The browser has made a Bad Request < /p >
break;
case 401:
echo ‘ < h1 > Authorization Required < /h1 >
echo ‘ < h2 > Error Code 401 < /h2 >
echo ‘ < > You have supplied the wrong information to access a secure ‘
‘resource < /p >
break;
case 403:
echo ‘ < h1 > Access Forbidden < /h1 >
echo ‘ < h2 > Error Code 403 < /h2 >
echo ‘ < > You have been denied access to this resource < /p >
break;
case 404:
echo ‘ < h1 > Page Not Found < /h1 >
echo ‘ < h2 > Error Code 404 < /h2 >
echo ‘ < > The page you are looking for cannot be found < /p >
break;
case 500:
echo ‘ < h1 > Internal Server Error < /h1 >
echo ‘ < h2 > Error Code 500 < /h2 >
echo ‘ < > The server has encountered an internal error < /p >
break;
default:
echo ‘ < h1 > Error Page < /h1 >
echo ‘ < > This is a custom error page < /p >
}
echo ‘ < > < a href=”mailto:sysadmin@example.com” > Contact < /a > the system ‘
‘administrator if you feel this to be in error < /p >
?
/body >
< /html >
page you know for certain doesn ’ t reside on your server, into the address bar You should see
the Page Not Found message on the screen, similar to the message shown in Figure 9 - 1
Trang 54 Another way to test or simulate the error messages, so that you can ensure you coded the page correctly, is to supply the page with the query string information via the browser For example, to simulate an Internal Server Error error message, type http://localhost/
error.php?500 into your address bar The page will use the query string information and run the code just as if there were an Internal Server Error on one of your pages The result will look pretty similar to the previous example, but will contain a different message The Internal Server Error page will look like the one shown in Figure 9 - 2 , displaying the Internal Server Error message on the screen
Figure 9-1
Trang 6How It Works
You have just created a simple error - handling PHP page You created a PHP page that will handle
the most common errors that servers encounter By using the query string information along with the
switch() statement, you are able to display custom error message pertinent to the error itself This is
useful if you don ’ t want Apache to display its somewhat cryptic - looking error message to your users
Apache ’ s ErrorDocument: Advanced Custom Error Page
Up until this point, you ’ ve been showing the user a custom error message only You can do countless
other things, such as e - mailing the administrator or webmaster of the site, so he or she can look into the
issue further should there be a problem with certain pages This is a great way for you to keep track of
your pages without having to check up on the server periodically More than likely, if you haven ’ t
received any error e - mails, there haven ’ t been problems with your server
Figure 9-2
Trang 7Try It Out Creating an Error E - Mail
In this exercise, you will create a script that generates an automatic e - mail that tells the administrator what time the error occurred, on what day, what the error was, what page generated the error, and what error message was displayed to the user who navigated to the page
1 Open your error.php file, and add to it the code highlighted here:
echo ‘ < h1 > Bad Request < /h1 >
echo ‘ < h2 > Error Code 400 < /h2 >
echo ‘ < > The browser has made a Bad Request < /p >
break;
case 401:
echo ‘ < h1 > Authorization Required < /h1 >
echo ‘ < h2 > Error Code 401 < /h2 >
echo ‘ < > You have supplied the wrong information to access a secure ‘ ‘resource < /p >
break;
case 403:
echo ‘ < h1 > Access Forbidden < /h1 >
echo ‘ < h2 > Error Code 403 < /h2 >
echo ‘ < > You have been denied access to this resource < /p >
break;
case 404:
echo ‘ < h1 > Page Not Found < /h1 >
echo ‘ < h2 > Error Code 404 < /h2 >
echo ‘ < > The page you are looking for cannot be found < /p >
break;
case 500:
echo ‘ < h1 > Internal Server Error < /h1 >
echo ‘ < h2 > Error Code 500 < /h2 >
echo ‘ < > The server has encountered an internal error < /p >
break;
default:
echo ‘ < h1 > Error Page < /h1 >
echo ‘ < > This is a custom error page < /p >
}
Trang 8echo ‘ < > < a href=”mailto:sysadmin@example.com” > Contact < /a > the system ‘
‘administrator if you feel this to be in error < /p >
$now = (isset($_SERVER[‘REQUEST_TIME’])) ? $_SERVER[‘REQUEST_TIME’] : time();
$page = (isset($_SERVER[‘REQUEST_URI’])) ? $_SERVER[‘REQUEST_URI’] :
‘unknown’;
$msg = wordwrap(‘A ‘ $_SERVER[‘QUERY_STRING’] ‘ error was encountered on ‘
date(‘F d, Y’, $now) ‘ at ‘ date(‘H:i:sa T’, $now) ‘ when a ‘
‘visitor attempted to view ‘ $page ‘.’);
The output that you see in the browser will be the same as you saw before, but behind the scenes, the
mail() function is used to send an e - mail to the administrator The mail() function allows you to
e - mail anyone you desire when an error occurs You will learn about the mail() function in more
detail in Chapter 11
That ’ s it! You just used Apache ’ s ErrorDocument directive to help you maintain your server
Error Handling and Creating Error - Handling
Pages with PHP
This section looks at how you can troubleshoot your PHP scripts using simple, logical steps But
first, you need to understand what PHP does when it encounters an error and what it does with
certain errors
When a PHP script gets executed and encounters an error, it displays a message in the browser
showing you what the error was Depending on what type of error occurred, the script may not finish
executing You are likely to run into these sorts of errors when writing your own scripts Don ’ t feel
ashamed if you receive errors; everybody makes errors when writing code, no matter what their level of
expertise Even though it is normal to receive errors during the development of your script, you don ’ t
want those errors (which are usually too complicated for the layperson to understand) popping up to
end users, when your site has gone live For this reason, it ’ s important to know how to catch those
unwanted errors and generate more user - friendly errors that let the user know that there will be a
solution forthcoming
Trang 9Error Types in PHP
There are 13 predefined error constants that correspond to different types of errors in PHP They are listed below, along with the E_ALL option Each of these can be called by either an integer value or a named constant, but because the integer value they represent may change between different versions of PHP (as the value of E_ALL did in PHP 5.2), we recommend only using the constant name
E_NOTICE : Nonfatal runtime notices that indicate that the script encountered something that
might be an error, but could also happen in the normal course of running a script
E_CORE_ERROR: Fatal errors that occur during PHP ’ s initial startup; the execution of the script is halted
E_STRICT : Runtime notices that suggest changes to your code that would ensure the best
interoperability and forward compatibility of your code
E_RECOVERABLE_ERROR: Catchable fatal errors that indicate that a probably dangerous error occurred, but did not leave the PHP ’ s execution engine in an unstable state
E_ALL : All errors and warnings combined .
Before version 6 of PHP, E_ALL combined all errors and warnings except for E_STRICT
Typically, you don ’ t have to worry about all of the error types; your main concern is with runtime errors such as notices, warnings, and errors, along with the user - generated equivalents The simple, more trivial errors, such as warnings, aren ’ t useful to users but can be helpful to you, since they notify you that you forgot to initialize a variable or something similar Because initializing variables is purely for your benefit while you are coding to track down errors before your web site launch, it is of no use to display these errors to users once your site goes live Your error - handling code helps resolve these cryptic errors, to offer helpful, user - friendly messages
Trang 10The three main types of errors discussed here are:
Fatal errors: Fatal runtime errors These indicate errors that the program can ’ t recover from
Script execution is halted
Warnings: Runtime warnings (nonfatal errors) Script execution is not halted
Notices: Runtime notices These indicate that the script has encountered something that could
indicate an error, but that could also happen in the normal course of running the script
Generating PHP Errors
Now let ’ s generate some errors so that you can check out what you need to do to resolve them Consider
this code snippet, for example:
< ?php
//set string with “Wrox” spelled wrong
$string_variable = ‘Worx books are awesome!’;
//try to use str_replace to replace Worx with Wrox
//this will generate an E_WARNING
//because of wrong parameter count
str_replace(‘Worx’, ‘Wrox’);
?
If you run this snippet, you should see the following error:
Warning: Wrong parameter count for str_replace() in C:\Program Files\Apache
Software Foundation\Apache2.2\htdocs\warning_test.php on line 8
The error occurred because str_replace() requires a third parameter for the function The third
parameter is the variable, $string_variable , or a string of text in which you want to search for the
first parameter, “ Worx, ” and replace it with “ Wrox ” Because this is a nonfatal error that does not halt
script execution, you can still run code after the point where the error occurred If you change the
snippet to this:
< ?php
//set string with “Wrox” spelled wrong
$string_variable = ‘Worx books are awesome!’;
//try to use str_replace to replace Worx with Wrox
//this will generate an E_WARNING
//because of wrong parameter count
str_replace(‘Worx’, ‘Wrox’);
//this is a non-fatal error, so the original
//variable should still show up after the warning
Trang 11then the string will continue to execute after the error, and will produce the following output:
Warning: Wrong parameter count for str_replace() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\warning_test.php on line 8
Worx books are great!
Next, we throw out a fatal error to show you how it produces different results when the error occurs
Let ’ s create a fatal error by using the following code:
< ?php//beginning of pageecho ‘Beginning’;
//we are going to make a call to//a function that doesn’t exist//this will generate an E_ERROR//and will halt script execution//after the call of the functionfatalerror();
//end of pageecho ‘End’;
//won’t be output due to the fatal error
?
This produces the following output:
BeginningFatal error: Call to undefined function: fatalerror() in C:\Program Files\
Apache Software Foundation\Apache2.2\htdocs\error_test.php on line 10
Notice that “ Beginning ” was output because it was before the function call, but “ End ” was not, because the fatal error halted the script execution You can suppress the fatal error calls by putting an ampersand
in front of the function call, like so: @fatalerror() This suppresses the error, but the script still halts its execution
The default error reporting does not show E_NOTICE errors However, you may want to show them during development Enabling E_NOTICE errors for debugging can warn you about possible bugs or bad programming practices For example, you might use something such as $row[variable] , but actually it is better to write this as $row[‘variable’] because PHP will try to treat variable as a constant If, however, it isn ’ t a constant, PHP assumes it to be a string for the array You can set error reporting by simply putting error_reporting(number) in your script , where number is the constant value shown earlier in the chapter
If you don ’ t know at what level your error reporting is set, you can simply call the error_reporting() function without any arguments, like this:
< ?phpecho error_reporting();
?
Trang 12By default, all error handling is handled by PHP ’ s built - in error handler, which tells you the error and
displays the message associated with that error The message displays the error type, the error message,
the filename, and the line number where the error occurred
Usually, letting PHP generate its own errors is fine, but with complicated applications you may want to
catch the errors so you can do something specific with an error, such as notifying an administrator so he
or she can look into the problem further
You will now create a custom error handler to catch the errors and display a more friendly error
echo ‘ < > Errors have occurred while executing this page Contact the ‘
‘ < a href=”mailto:admin@example.com” > administrator < /a > to report
it < /p >
echo ‘ < hr/ >
echo ‘ < > < > Error Type: < /b > ‘ $e_type ‘ < br/ >
echo ‘ < > Error Message: < /b > ‘ $e_message ‘ < br/ >
echo ‘ < > Filename: < /b > ‘ $e_file ‘ < br/ >
echo ‘ < > Line Number: < /b > ‘ $e_line ‘ < /p >
//set string with “Wrox” spelled wrong
$string_variable = ‘Worx books are awesome!’;
//try to use str_replace to replace Worx with Wrox
//this will generate an E_WARNING
//because of wrong parameter count
str_replace(‘Worx’, ‘Wrox’);
?
2 Save the file as custom_error.php , and open it in your browser The output should look
similar to that in Figure 9 - 3
Trang 133 Because your error handler is user - defined, you can catch the errors, and you can recreate the error messages based on the error type Edit the custom_error.php file like this:
< ?phpfunction my_error_handler($e_type, $e_message, $e_file, $e_line) {// Delete these lines
echo ‘ < > < > Error Type: < /b > ‘ $e_type ‘ < br/ >
echo ‘ < > Error Message: < /b > ‘ $e_message ‘ < br/ >
echo ‘ < > Filename: < /b > ‘ $e_file ‘ < br/ >
echo ‘ < > Line Number: < /b > ‘ $e_line ‘ < /p >
// End deleted lines switch ($e_type) { case E_ERROR:
echo ‘ < h1 > Fatal Error < /h1 >
echo ‘ < > A fatal error has occurred in ‘ $e_file ‘ at line ‘ $e_line ‘ < br/ > ’ $e_message ‘ < /p >
die();
break;
Figure 9-3
Trang 14echo ‘ < > A warning has occurred in ‘ $e_file ‘ at line ‘ $e_line
//set string with “Wrox” spelled wrong
$string_variable = ‘Worx books are awesome!’;
//try to use str_replace to replace Worx with Wrox
//this will generate an E_WARNING
//because of wrong parameter count
str_replace(‘Worx’, ‘Wrox’);
?
4 Save the file, and load it in your browser The results should look like Figure 9 - 4 One of the
earlier code snippets you created produced a fatal error, which is why the E_ERROR case was
called in the switch statement This sort of handler is nice to use to trap any sort of error and
perform different actions based on the error
Trang 15How It Works Creating custom error message gives you nearly full control over your pages, regardless of success or failure when they are executed What you have done is create a function called my_error_handler , which will catch the type of error, the error message, the file in which the error occurred, and the line
in which the error occurred By knowing those details, you can take whatever steps are necessary to ensure the success of your web site The heart of the function ’ s logic relies on a switch() construct, where you are able to display a certain error message, send specific error message e - mails, or do whatever else you may want, depending on which error was served up by Apache For example, if you were to encounter an E_ERROR , the code would run the case E_ERROR: section of the switch() Depending on which section of the switch() was used, you will see a different error message
When trapping errors, you can display whatever you want to display, but you may not want the user to see the error message you created previously You can create an error message that simply says there was
an error on the page Then you can apologize for the inconvenience and allow the user to go to another page Finally, you can write the error message to a log file, write it to a database, or send it to the webmaster or administrator via e - mail, so that person can further review the error
We personally prefer the e - mail method because it requires that the person be notified of the problem right away, and it doesn ’ t require him or her to check the database or log files periodically The only problem with this method occurs if there are a lot of requests to the page where the error is occurring; in that case the admin will be bombarded with e - mails (Of course, this could light the proverbial fire under him or her to get the issue fixed!)
For this exercise, you ’ ll set up your full - featured error handler to do just what you want it to You can then include this page in all your pages, so you can trap all the errors without using PHP ’ s built - in handler
1 Open your text editor, and enter the following code:
< ?php//create your error handler functionfunction my_error_handler($e_type, $e_message, $e_file, $e_line) {
$msg = ‘Errors have occurred while executing a page.’ “\n\n”;
$msg = ‘Error Type: ‘ $e_type “\n”;
$msg = ‘Error Message: ‘ $e_message “\n”;
$msg = ‘Filename: ‘ $e_file “\n”;
$msg = ‘Line Number: ‘ $e_number “\n”;
$msg = wordwrap($msg, 75);
switch($error_type) { case E_ERROR:
mail(‘admin@example.com’, ‘Fatal Error from Website’, $msg);
die();
break;
case E_WARNING: