Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... Copy the code you made in Chapter 6 into a new directory, open the movie.phpscript, andmodify it as shown in t
Trang 12. Have a page on your site with funny photographs or cartoons and allow your users to write thecaption for them Place the text in a speech bubble that is appropriately sized based on thelength of the caption they submit.
3. Create a page for kids where they can choose different heads, bodies, and tails from animals,and put them together to make a new creation and a new image Or create a virtual paper dollsite where kids can place different outfits on a model, then save the images they create
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 2Validating User Input
If you plan to accept user input on your site, you have to be prepared for mistakes This could besimple human error, or a deliberate attempt to circumvent your Web forms The most commonhuman errors include basic typographical errors and format errors — failing to give a year in adate, for example Deliberate errors could be a user who doesn’t want to provide his e-mailaddress, or it could be an attacker deliberately trying to corrupt your database with unexpectedcharacters No matter what the source, your script needs to be able to handle incorrect input, usu-ally by identifying the bad data and returning the user to the form page with an appropriate errormessage This chapter covers user input validation, including:
❑ Validating simple string values
❑ Validating integer values
❑ Validating formatted text input
Users Are Users Are Users Consider an example: You work in a bank You are developing a new system to allow the employ-ees to manage a customer account updating process on the company intranet You use your well-known MM-DD-YYYY format for the date It all works quite well when testing, but when put inproduction, your users say it doesn’t work Why? Because all your company systems use the ISO
8601 YYYY-MM-DD date format (a standard used in many systems because the date can be sortedalphabetically) Your users are confused between the two different formats and input wrong infor-mation in the system If the data is in the wrong format, you can end up with a corrupted database
or trigger errors in your application
You can avoid this by using well-known formats and validating the user input When you expect
an integer value, for example, you can check that it is an integer before you try to use it It’s a ple enough rule, and you’ll learn how to do it later in this chapter
sim-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 3Incorporating Validation into the Movie Site
To really understand the role of user input and validation, you need to see it in action So, first you need
to add a few fields to your beloved movie database The modifications are all in the movietable
The movie application provides a lot of opportunities to check for user input You will need to add a fewfeatures to the application, however, to provide more case studies It will also help you to review whatyou learned in the previous chapters
Add a movie_releasefield INT(11)with default value 0 after the existingmovie_yearfield, as shown
in Figure 8-1 This allows you to store a timestamp for the movie release date Then add a field named
movie_ratingat the end of the table type TINYINT (2) That information holds the movie rating yougave the movie when viewing it (see Figure 8-2) This rating goes from 0 to 10
Figure 8-1
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 4Try It Out Adapting Your Script to the User Input
In this exercise, you’ll be making sure that the script can adapt when the user fails to enter all the fields
1. Copy the code you made in Chapter 6 into a new directory, open the movie.phpscript, andmodify it as shown in the highlighted lines:
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 5$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
mysql_select_db(‘moviesite’, $link)
or die ( mysql_error());
$peoplesql = “SELECT * FROM people”;
$result = mysql_query($peoplesql)
or die(“Invalid query: “ mysql_error());
while ($row = mysql_fetch_array($result)) {
$people[$row[‘people_id’]] = $row[‘people_fullname’];
}
switch ($_GET[‘action’]) {
case “edit”:
$moviesql = “SELECT * FROM movie “
“WHERE movie_id = ‘“ $_GET[‘id’] “‘“;
echo $_GET[‘action’]; ?>&type=movie&id=<?php
if (isset($_GET[‘id’])) { echo $_GET[‘id’]; } ?>” method=”post”>
Trang 6“font-weight:bold\”>” nl2br(urldecode($_GET[‘error’]))
“</div><br />”;
}
?>
<table border=”0” width=”750” cellspacing=”1”
cellpadding=”3” bgcolor=”#353535” align=”center”>
<tr>
<td bgcolor=”#FFFFFF” width=”30%”>Movie Name</td>
<td bgcolor=”#FFFFFF” width=”70%”>
<input type=”text” name=”movie_name”
value=”<?php echo $movie_name?>”>
<select id=”game” name=”movie_type” style=”width:150px”>
<option value=”” selected>Select a type </option>
<?php
$sql = “SELECT movietype_id, movietype_label “
“FROM movietype ORDER BY movietype_label”;
$result = mysql_query($sql)
or die(“<font color=\”#FF0000\”>Query Error</font>” mysql_error());
while ($row = mysql_fetch_array($result)) {
<option value=”<?php echo $year; ?>”
<?php echo $selected; ?>><?php echo $year; ?></option>
<?php}
?>
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 7<option value=”<?php echo $people_id; ?>”
<?php echo $selected; ?>><?php echo $people_fullname;
<option value=”<?php echo $people_id; ?>”
<?php echo $selected; ?>><?php echo $people_fullname;
<td bgcolor=”#FFFFFF” colspan=”2” align=”center”>
<input type=”submit” name=”submit”
value=”<?php echo $_GET[‘action’]; ?>”>
Trang 8</body>
</html>
2. Save the file as movie.phpand upload the new code to your work directory
3. Open the commit.phpscript and modify it as shown in the highlighted lines:
<?php// COMMIT ADD AND EDITS
$error = ‘’;
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
mysql_select_db(‘moviesite’, $link)
or die ( mysql_error());
switch ($_GET[‘action’]) {case “edit”:
switch ($_GET[‘type’]) {case “people”:
$sql = “UPDATE people SET “
$error “&id=” $_GET[‘id’] );
}break;
}break;
case “add”:
switch ($_GET[‘type’]) {case “people”:
$sql = “INSERT INTO people (people_fullname) “
“VALUES (‘“ $_POST[‘people_fullname’] “‘)”;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 9}break;
4. Save the file as commit.phpand upload it to your server
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 105. Now open your browser and go to http://localhost/chapter8/index.php(adapt thisURL to fit your setup) and try adding a movie with no name, as shown in Figure 8-3.
Figure 8-3Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 116. Now try to enter a new movie without setting the year and the movie type (see Figure 8-4).
Figure 8-4
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 127. Edit a movie from the index and try deleting the name and submitting the form (see Figure 8-5).
Figure 8-5Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 138. Notice the error message stating the mistake made in filling in the form (see Figure 8-6).
Figure 8-6
How It Works
When the form passes information to the commit script, the data has to be verified In this case, you use
a simple verification method: The empty()function returns trueif the string is empty and falseif not
To ensure that the user did not submit the form with a simple space in the movie name field, you use
trim()on the field’s content to eliminate any space leading or trailing the string (Some people like totrigger errors in Web sites by entering erroneous input; don’t make their job easy.)
At the same time, if an error is detected, you add a message to the $errorvariable that collects all the errormessages The error messages are URL encoded before being added to the code (See urlencodeand
urldecodefunctions in the manual; for more information, check the PHP Web site at www.php.net/url.)
Trang 14Once you are sure that an error has occurred, you redirect the user to the form with an error messagestating the problem The error message is URL encoded to ensure that it will be passed to the movie.php
script without being corrupted
if (empty($error)) {
} else {header(“location:movie.php?action=add&error=” $error);
}
Once redirected to the form, the system needs to display the decoded error message
<?
if (!empty($_GET[‘error’])) {echo “<div align=\”center\” “
This displays a rather colorful message that your user will not miss
The update itself is performed at the end of the code, along with all the controls and debug messagesyou need
if (isset($sql) && !empty($sql)) {echo “<! ”.$sql.” >”;
If the $sqlvariable is not previously set (which could happen if the page is called out of context), thecode will not try to execute and will do nothing (Note that it would be a good exercise for you to code aresponse to this occurrence, such as a message or a logging of the error in the database.)
Checking for Format ErrorsChecking for errors in dates or other formatted data is a requirement in most systems because userscan’t always be guided in their input You should always check the data that the user enters if yourequire a specific format or set of values
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 15At this point, you need the feared and powerful regular expressions The regular expressions allow you to
define a pattern and check to see if it can be applied to your data It’s very useful to check for dates,Social Security numbers, and any data that has to respect a predefined set of format requirements (It helps
to be sure to always indicate the format in the source field.)
In this exercise, you’ll change a few pages so that you can check the format of the dates the user enters
1. Open the well-known movie.phpfile and modify it as follows (modifications are highlighted):
<?php
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
mysql_select_db(‘moviesite’, $link)
or die(mysql_error());
$peoplesql = “SELECT * FROM people”;
$result = mysql_query($peoplesql)
or die(“Invalid query: “ mysql_error());
while ($row = mysql_fetch_array($result)) {
$people[$row[‘people_id’]] = $row[‘people_fullname’];
}
switch ($_GET[‘action’]) {
case “edit”:
$moviesql = “SELECT * FROM movie “
“WHERE movie_id = ‘“ $_GET[‘id’] “‘“;
Trang 16<title><?php echo $_GET[‘action’]; ?> movie</title>
if (isset($_GET[‘id’])) { echo $_GET[‘id’]; } ?>” method=”post”>
<?php
if (!empty($_GET[‘error’])) {echo “<div align=\”center\” “
<table border=”0” width=”750” cellspacing=”1”
cellpadding=”3” bgcolor=”#353535” align=”center”>
<tr>
<td bgcolor=”#FFFFFF” width=”30%”>Movie Name</td>
<td bgcolor=”#FFFFFF” width=”70%”>
<input type=”text” name=”movie_name”
value=”<?php echo $movie_name?>”>
<select id=”game” name=”movie_type” style=”width:150px”>
<option value=”” selected>Select a type </option>
<?php
$sql = “SELECT movietype_id, movietype_label “
“FROM movietype ORDER BY movietype_label”;
$result = mysql_query($sql)
or die(“<font color=\”#FF0000\”>Query Error</font>” mysql_error());
while ($row = mysql_fetch_array($result)) {
Trang 17<option value=”” selected>Select a year </option>
<option value=”<?php echo $year; ?>”
<?php echo $selected; ?>><?php echo $year; ?></option>
<option value=”<?php echo $people_id; ?>”
<?php echo $selected; ?>><?php echo $people_fullname;
<option value=”<?php echo $people_id; ?>”
<?php echo $selected; ?>><?php echo $people_fullname;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 18<?php}
<input type=”text” name=”movie_release”
value=”<?php echo date(“d-m-Y”, $movie_release); ?>”>
<input type=”text” name=”movie_rating”
value=”<?php echo $movie_rating; ?>”>
</td>
</tr>
<tr>
<td bgcolor=”#FFFFFF” colspan=”” align=”center”>
<input type=”submit” name=”submit”
value=”<?php echo $_GET[‘action’]; ?>”>
$error = ‘’;
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
mysql_select_db(‘moviesite’, $link)
or die ( mysql_error());
switch ($_GET[‘action’]) {case “edit”:
switch ($_GET[‘type’]) {case “people”:
$sql = “UPDATE people SET “
Trang 19$error “&id=” $_GET[‘id’]);
}break;
}break;
case “add”:
switch ($_GET[‘type’]) {case “people”:
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 20$sql = “INSERT INTO people (people_fullname) “
}break;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 213. Now save the files, upload them, and open your browser to the site index
4. Click any movie and try entering 2003-10-10 in the release date field You will be brought back
to the form with a nice, yet very explicit, message telling you what format to use, as shown inFigure 8-7
Figure 8-7
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 225. Try entering alphanumeric values in the rating field, as in Figure 8-8 (which could easily havebeen a drop-down but is a text field for the purpose of the exercise).
Figure 8-8
If the entered value is not in the 0 to 10 range, it will be refused (Note that the decimals are notmanaged in this code and will be lost.)
How It WorksFirst, let’s look into the type validating functions In the commit.phpcode, you use the is_numeric()
function This function returns a Boolean TRUE if the value is indeed numeric and FALSE if not More ofthese validating functions are available, including:
❑ is_string, which checks to see if the value is of the string format
❑ is_bool, which checks for Boolean type (TRUE, FALSE, 0, or 1)
❑ is_array, which tells you if the variable holds an arraySimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 23❑ is_object, which determines if the variable stores an object (remember this one when you tryobject-oriented coding using PHP; it is very useful)
These functions are all documented in the PHP manual at www.php.net/variables.
In this instance, the use of is_numericallows you to make sure that the user has entered a numeric value
The code first cleans up the value of leading and trailing spaces with the trim()function (always try
to be prepared for typos and mishaps) and then tests to see if the value is numeric If it’s not, the errormessage queue is fed; if it is, the code tests the value to see if it is between 0 and 10 If the value is notbetween 0 and 10, it adds an error message to the error message queue
The date validation is almost as simple to understand, if you know about regular expressions Here’s acloser look at it:
Trang 24match, but not 2 The same logic applies to the [0-9]{4}statement: The only difference is that you areexpecting four digits in the number, which indicate the year part of the date
So, in English, it means “I want my string to start with a number with two digits, followed by a hyphen,and then another group of two digits, and then a hyphen, and finish with a four-digit number.”
This is exactly what your regular expression says If the string matches your condition, you will split it
in three different chunks, each chunk delimited with the parentheses
This cutting is performed by the ereg()function If the $movie_releasestring matches the pattern,
eregwill cut the string into parts and then store each part as an element of the $reldatepartarray
Be sure to read the PHP manual about regular expressions at www.php.net/regexand consult a few tutorials to understand the real power of using regular expressions (You can find a good starting tutorial
at www.phpbuilder.com/columns/dario19990616.php3.)
If the user entered the date 02-03-2004, the array would be as follows:
Array([0] => 02-03-2004[1] => 02
[2] => 03[3] => 2004)
As you can see here, the first index holds the whole string, and each remaining index holds a cut-off part
of the string, delimited by the parentheses
Now that you have the date in an understandable format, you can change it into a timestamp using the
mktime()function, which allows you to create a timestamp from chunks of dates It is also a very usefulfunction to manipulate dates
$movie_release = mktime(0, 0, 0, $reldatepart[‘2’],
$reldatepart[‘1’],
$reldatepart[‘3’]);
This code stores a timestamp from the day, month, and year information fed to the system in the
$movie_releasevariable The format is int mktime(int hour, int minute, int second, int month,
int day, int year) The returned value is the number of seconds between January 1, 1970, and the ified date
spec-See documentation at www.php.net/mktimefor additional information regarding optional ters such as daylight saving flag.
parame-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 25If mktimefails to create a timestamp from the date you passed to it, it will return -1 This happens whenthe input is invalid, although it matches the regular expression For example, 99-99-9999 will pass theregular expression test but is obviously not a valid date To be sure that the date is indeed a date, youtest for the return value from mktimeand respond accordingly.
if ($movie_release == ‘-1’) {
$error = “Please+enter+a+real+date+”
“with+the+dd-mm-yyyy+format%21%0D%0A”;
}
In this case, a false date entry triggers an error message asking for a valid date
Here’s an alternative technique: You could have performed the same timestamp generation using SQL.Many things that PHP does on the string manipulation side can be done straight from SQL, as shown here:
if (!ereg(“([0-9]{2})-([0-9]{2})-([0-9]{4})”,
$movie_release,
$reldatepart) || empty($movie_release)) {
See documentation on MySQLdateand timefunctions at www.mysql.com/doc/en/
Date_and_time_functions.html.
Summar y
Validating user data is all about being prepared for the worst Users make mistakes — that’s the nature
of users Most errors are unintentional, but some are made intentionally to deny the service It happensevery day The developer has to help the system deal with user input errors
Regular expressions help you meet many user input validation challenges Learning how to use them isoften the key to success in an interactive system
Exercise
1. Add validation to make the lead actor and director selections required
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 26Handling and Avoiding Errors
You will probably be spending a fair amount of time contemplating errors in your code, as domost Web developers when they start programming No matter how good you are, how well youcode, how long you have been coding, or how hard you try, you will encounter times when youhave errors in your code
It is of the utmost importance that you know how to handle your errors and debug your owncode Being able to efficiently and properly debug your code is an invaluable time-saver; and inWeb development, $time == $money!
Luckily, PHP comes with a full-featured Applications Programming Interface (API) that providesyou with many ways to trap and resolve those unwanted errors PHP also allows you to use theAPI to capture the errors and create your own custom error functions or pages These features areuseful 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 totrap errors and customize them; 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.conffile to ate custom error pages with PHP so visitors to your site don’t see the old, boring, server-createderror pages You have limitless possibilities when creating these custom messages As with thePHP error-catching pages, you can have the ErrorDocumentcall PHP pages to do whatever youwould like them to do — from simply displaying a friendly error message to the user to e-mailing
cre-a system cre-administrcre-ator to notify him or her of the fcre-ailure
Unlike PHP error pages, the Apache ErrorDocument pages are used more for instances of missingpages (that is, a “Page Not Found” error or “Forbidden access” error pages and other requests ofthat sort) So, if someone visits your site, and he or she runs into the “Page Not Found” error page,Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 27the script will e-mail the administrator and he or she can in turn check to see whether this was a validrequest and there is something wrong with the page or server, or whether someone was just looking forpages or trying to sniff around where they weren’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 upand running with the fewest end-user problems or complaints If you rely on people contacting you totell you about errors on your site, you will never get any decent input Allowing the server to do this foryou will greatly increase your success at running a smooth server This section first looks at Apache’sErrorDocument method of error handling
Try It Out Using Apache’s ErrorDocument Method
First of all, you need to make some changes to the httpd.conffile to allow you to create a custom errorpage 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.conffile, and around line 750 or so, you will find some lines that looklike this (if you do not have access to httpd.conf, the following can usually be added to a
.htaccessfile in the base directory of your Web site):
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
2. Change that information to the following, then restart Apache:
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
You have just edited Apache’s configuration file to help you with error handling By using the
ErrorDocumentdirective, 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 BeFound” page, you can redirect it to a page you have created to look like your Web site but still get theSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 28message through to the user that there has been a problem You can do that with any and all error sages that the server can encounter.
mes-Many ErrorDocumentcodes exist, but we will focus on the error messages you see typically in day Web browsing:
501 error code, you would simply add ErrorDocument 501 /error.php?501 to your code and add the
error handling in the error.phppage, which you’ll see shortly
Next, you’ll see a simple way to show the user error messages, and then get into some more complexways to notify the Webmaster of errors occurring on the Web site by using the mail()command thatyou learned previously
Try It Out Displaying Custom Error Messages
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:
<?php
$error_no = $_SERVER[‘QUERY_STRING’];
switch ($error_no) {case 400:
$error_output = “<h1>"Bad Request" Error Page - “
“(Error Code 400)</h1>”;
$error_output = “The browser has made a Bad Request<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
break;
case 401:
$error_output = “<h1>"Authorization Required" “
“Error Page - (Error Code 401)</h1>”;
$error_output = “You have supplied the wrong information to “
“access a secure area<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 29“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
break;
case 403:
$error_output = “<h1>"Forbidden Access" Error Page - “
“(Error Code 403)</h1>”;
$error_output = “You are denied access to this area<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
break;
case 500:
$error_output = “<h1>"Internal Server Error" “
“Error Page – (Error Code 500)</h1>”;
$error_output = “The server has encountered an internal “
“error<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
break;
default:
$error_output = “<h1>Error Page</h1>”;
$error_output = “This is the custom error Page<br>”;
$error_output = “You should be <a href=\”index.php\”>here</a>”;
3. Open your browser and type http://localhost/asdf/qwerty/page.html, or any other page you
know for certain doesn’t reside on your server, into the address bar You should see the “PageNot Found” message on the screen, similar to the message shown in Figure 9-1
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 30Figure 9-1
4. Another way to test or simulate the error messages so that you can ensure you coded the pagecorrectly 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 ifthere were an Internal Server Error on one of your pages The result will look pretty similar tothe previous example but will contain a different message The “Internal Server Error” pagewill look like the one shown in Figure 9-2, displaying the “Internal Server Error” message onthe screen
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 31Apache’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 otherthings, such as e-mailing the administrator or Webmaster of the site so he or she can look into the issue fur-ther should there be a problem with certain pages This is a great way for you to keep track of your pageswithout having to check up on the server periodically More than likely, if you haven’t received any errore-mails, there haven’t been problems with your server
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 32Try It Out Creating an Error E-Mail
In this exercise, you will create a script that generates an automatic e-mail that tells the administratorwhat time the error occurred, on what day, what the error was, what page generated the error, and whaterror message was displayed to the user who navigated to the page
1. Open your error.phpfile You’re going to change the code substantially, so if you want to keepthe original file, save a copy under the original name
2. Enter the following code (This is almost completely new code, so we won’t show you thechanged lines with highlighting this time.)
<?phpfunction email_admin($error_no,
$error_output,
$full_date,
$full_time,
$request_page) {
$to = “Administrator <admin@yourdomain.com>”;
$subject = “Apache Error Generation”;
$body = “Error received was a <b>” $error_no “</b> error.<br>”;
$body = “The page that generated the error was: <b>”
$headers = “Content-type: text/html; charset=iso-8859-1\r\n”;
$headers = “From: Apache Error <host@yourdomain.com>\r\n”;
Trang 33$error_output = “The browser has made a Bad Request<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
$error_output = “You have supplied the wrong information to “
“access a secure area<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
$error_output = “You are denied access to this area<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
Trang 34$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
$error_output = “The server has encountered “
“an internal error<br>”;
$error_output = “<a href=\”mailto:sysadmin@localhost.com\”>”
“Contact</a> the system administrator”;
$error_output = “ if you feel this to be in error”;
$error_output = “<h1>Error Page</h1>”;
$error_output = “This is the custom error Page<br>”;
$error_output = “You should be <a href=\”index.php\”>here</a>”;
Trang 35How It Works
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 Some other PHP functions, such as
getdate(), are used to note the time and day the error occurred The mail()function allows you toe-mail anyone you desire when an error occurs You will learn about the mail()function in more detail
in Chapter 11 Also, by using getdate(), you are able to retrieve when exactly the error occurred soyou can make note of the error’s time of occurrence You can get the date in many ways, including the
date()function, but the getdate()function is a little easier to decipher We threw in some functionpractice for you to get the hang of sending variables as parameters to and from functions Now theadministrator or Webmaster will be getting an HTML-formatted e-mail concerning the error messagethat the user received when he or she happened to go to that page
That’s it! You just used Apache’s ErrorDocument directive to help you maintain your server
Error Handling and Creating Error Handling
Error Types in PHP
There are 12 types of errors in PHP, which are listed in the following table, along with the Report AllErrors option Each of these can be called by either an integer value or a named constant Slight changeshave been made as of PHP5: the addition of E_STRICT, and that E_ALLdoes not include E_STRICT
Error Integer Value NAMED CONSTANT
E_ERROR 1 Fatal runtime error
E_WARNING 2 Non-fatal runtime error
E_PARSE 4 Compile-time parse error
E_NOTICE 8 Non-fatal runtime notice
E_CORE_ERROR 16 Fatal error occurring at startup
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 36Error Integer Value NAMED CONSTANT
E_CORE_WARNINGS 32 Non-fatal runtime error caused by initial startup
E_COMPILE_WARNING 128 Non-fatal compile-time error
E_USER_ERROR 256 User-generated error by PHP function
E_ALL 2047 All errors and warnings reported
E_STRICT 2048 Run-time notices When enabled, will suggest
changes to your code to ensure forward compatibility
Typically, you don’t have to worry about all of the error types; your main concern is with runtime errorssuch as notices, warnings, and errors, along with the user-generated equivalents The simple, more triv-ial errors, such as warnings, aren’t useful to users or yourself, since they simply notify you that you for-got to initialize a variable or something similar Because initializing variables is purely for your benefitwhile you are coding to track down errors before your Web site launch, it is of no use to display theseerrors to users once your Web site goes live Your error-handling code helps resolve these cryptic errors
to offer helpful, user-friendly messages
The three main types of errors discussed in full here are:
❑ Fatal errors: Fatal runtime errors These indicate errors that the program can’t recover from.Script execution is halted
❑ Warnings:Runtime warnings (non-fatal errors) Script execution is not halted
❑ Notices: Runtime notices These indicate that the script has encountered something that couldindicate an error, but 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 Considerthis code snippet, for example:
<?php//set string with “Wrox” spelled wrong
$string_variable = “Worx books are great!”;
//try to use str_replace to replace Worx with Wrox//this will generate an E_WARNING
//because of wrong parameter countstr_replace(“Worx”, “Wrox”);
?>
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 37If you run this snippet, you should see the following error:
Warning: Wrong parameter count for str_replace() in
c:\FoxServ\www\errorhandling\error1.php on line 8
The error occurred because str_replacerequires 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 non-fatal 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 great!”;
//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
echo $string_variable;
?>
The string will continue to execute after the error, and will produce the following output:
Warning: Wrong parameter count for str_replace() in
c:\FoxServ\www\errorhandling\error1.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 page
echo “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 function
Fatal error: Call to undefined function: fatalerror() in
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 38Notice that “Beginning” was output because it was before the function call, but “End” was not becausethe 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 haltsits execution
As of PHP4 the default error reporting does not show E_NOTICEerrors However, you may want to show them during development Enabling E_NOTICEerrors for debugging can warn you about possible bugs or bad programming practices For example, you might use something such as $row[variable], but actu- ally it is better to write this as $row[‘variable’]because PHP will try and 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) , where number is the constant value in the table shown earlier in the chapter, in your PHP page.
If you don’t know at what level your error reporting is set, you can simply run the error_reporting()
function without any arguments, like this:
<?phpecho error_reporting();
?>
By default, all error handling is handled by PHP’s built-in error handler, which tells you the error anddisplays 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
You may have noticed an error similar to this one in a previous code snippet:
Warning: Wrong parameter count for str_replace() in c:\FoxServ\www\errorhandling\error1.php on line 8
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 the error, such as notifying an administrator so he
or she can look into the problem further
Try It Out Creating a Custom Error HandlerYou will now create a custom error handler to catch the errors and display a more friendly error message
1. Edit the script used in the previous examples like this:
<?php//create your error handler functionfunction handler($error_type,
$error_message,
$error_file,
$error_line) {echo “<h1>Page Error</h1>”;
echo “Errors have occurred while executing this page Contact the “;
echo “<a href=\”mailto:admin@yourdomain.com\”>administrator</a> “
“to report errors<br><br>”;
echo “<b>Information Generated</b><br><br>”;
echo “<b>Error Type:</b> $error_type<br>”;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 39echo “<b>Error Message:</b> $error_message<br>”;
echo “<b>Error Filename:</b> $error_file<br>”;
echo “<b>Error Line:</b> $error_line”;
}
//set the error handler to be used
set_error_handler(“handler”);
//set string with “Wrox” spelled wrong
$string_variable = “Worx books are great!”;
//try to use str_replace to replace Worx with Wrox
//this will generate an E_WARNING
//because of wrong parameter count
Trang 403. Because your error handler is user-defined, you can catch the errors, and you can re-create theerror messages based on the error type Create a snippet for this sort of error handler by editingyour custom_error.phpfile like this:
<?php//create your error handler functionfunction handler($error_type,
$error_message,
$error_file,
$error_line) {switch ($error_type) {
//fatal errorcase E_ERROR:
echo “<h1>Fatal Error</h1>”;
die(“A fatal error has occured at line $error_line of file “
“$error_file.<br>”
“Error message created was "$error_message"”);
break;
//warningscase E_WARNING:
//don’t show notice errorsbreak;
}}//set the error handler to be usedset_error_handler(“handler”);
//set string with “Wrox” spelled wrong
$string_variable = “Worx books are great!”;
//try to use str_replace to replace Worx with Wrox//this will generate an E_WARNING
//because of wrong parameter countstr_replace(“Worx”, “Wrox”);