Consider a scenario in which your site offers an HTML form from which the
user could subscribe to a newsletter by submitting his or her e-mail address. Several
outcomes are possible. For example, the user could do one of the following:
??? Provide a valid e-mail address
??? Provide an invalid e-mail address
CHAPTER 8 ?– ERRO R AND EXCEPTION HANDL ING 227
??? Neglect to enter any e-mail address at all
??? Attempt to mount an attack such as a SQL injection
Proper exception handling will account for all such scenarios. However, you need
to provide a means for catching each exception. Thankfully, this is easily possible
with PHP. Listing 8-3 shows the code that satisfies this requirement.
Listing 8-3. Catching Multiple Exceptions
/* The Invalid_Email_Exception class is responsible for notifying the site
administrator in the case that the e-mail is deemed invalid. */
class Invalid_Email_Exception extends Exception {
function __construct($message, $email) {
$this->message = $message;
$this->notifyAdmin($email);
}
private function notifyAdmin($email) {
mail("admin@example.org","INVALID
EMAIL",$email,"From:web@example.com");
}
}
/* The Subscribe class is responsible for validating an e-mail address
and adding the user e-mail address to the database. */
class Subscribe {
function validateEmail($email) {
try {
228 CHAPTER 8 ?– ERRO R AND EXCEPTION HANDL ING
if ($email == "") {
throw new Exception("You must enter an e-mail address!");
} else {
list($user,$domain) = explode("@", $email);
if (! checkdnsrr($domain, "MX"))
throw new Invalid_Email_Exception(
"Invalid e-mail address!", $email);
else
return 1;
}
} catch (Exception $e) {
echo $e->getMessage();
} catch (Invalid_Email_Exception $e) {
echo $e->getMessage();
}
}
/* This method would presumably add the user's e-mail address to
a database.
Pages:
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306