Team LiB
Previous Section Next Section

Causing Errors

So far, we've looked at how to deal with errors generated internally by PHP. There will also be times during the course of your script's execution when a syntactically and procedurally valid condition just doesn't make sense for your program flow. When these types of conditions occur, your script can raise an error using the built-in function trigger_error(). Its prototype is as follows:

bool trigger_error(string error_msg[, int error_type])

error_msg will be passed into the default error handler or a custom error handler, if one is defined. error_type is optional and may be set to any one of the following:

E_USER_NOTICE, E_USER_WARNING, or E_USER_ERROR. If no error_type is specified, E_USER_NOTICE is assumed. If an invalid error_type is passed, TRigger_error() will return false and not raise the error.

An example of this might be a set of data validation routines where user-supplied data is checked against a set of criteria. If the data doesn't pass validation, we may want to raise an error. Consider the following code snippet that might be found in a login script:

if (isset($_POST['submit']) && 
(empty($_POST['username']) || 
 empty($_POST['password']))) {
 trigger_error("Form submitted, but username and/or password not provided
", E_USER_ERROR);
}

Here our login script expects a username and password pair whenever the Submit button is pressed. If either of these values is empty, the user has done something wrong, so we raise an error that will halt execution of the script.

    Team LiB
    Previous Section Next Section