Listing 5. Error Reporting through Assertions

<?php

/* You can toggle assertions throughout your entire
   application by switching ASSERT_ACTIVE to 1 or 0
*/
assert_options(ASSERT_ACTIVE,1);

/* We do want the application to exit when an
   assertion fails. (in this example)
*/
assert_options(ASSERT_BAIL,1);

/* In our example, we will do the error reporting
   ourselves so we turn off the default warnings
*/
assert_options(ASSERT_WARNING,0);

/* display_error will be the name of our custom
   function that will be called is an assertion
   fails
*/
assert_options(ASSERT_CALLBACK, "display_error");

$email = strtolower($_POST['email']);
$parts = array();

// Building your regular expression
$regex = "^([.\'a-z0-9]+)@([.\'a-z0-9]+)$";

/* Checking for valid format and splitting
   the email address at the same time
   Note the special formatting. Everything
   is in quotation marks and the error is
   commented. We will extract this error
   later through regular expressions.
*/
assert("ereg(\$regex, \$email, \$parts); /*
       Invalid email address: $email */");

/* This block will not be executed if the
   assertion fails so we can safely go on */
$username = $parts[1];
echo "Welcome home, " . $username;

// This is our ASSERT_CALLBACK function
function display_error($file, $line, $error) {

    // This block will extract the comment message
    $regex = "(.*)/\* (.*)\*/";
    $parts = array();
    ereg($regex, $error, $parts);
    $msg = $parts[2];

    // And we can output a nice little report
    echo "
    <table bgcolor=\"#bbbbee\">
    <tr><td colspan='2' align='center'>
    <b>Error Report</b>
    </td></tr>
    <tr><td>File:</td><td>$file</td></tr>
    <tr><td>Line:</td><td>$line</td></tr>
    <tr><td>Message:</td><td>$msg</td></tr>
    ";

}

?>

