PHP Try, Throw and Catch

Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008

0

Exceptions can occur in your program and you need to handle them to have your code going on. But how would you know which code is going to produce an error.

PHP exception handling provides some easy steps to deal with the exceptions:

  • track where an error is produced
  • throw the error to some handler
  • catch the appropriate error and continue with the execution

A proper exception code includes:

  • Try – It encloses the block of code or the function which is doubted to produce an exception. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is thrown automatically.
  • Throw – Throw lets you trigger an error manually.
  • Catch – It contains the code to handle the exceptions. A “catch” block retrieves an exception and creates an object containing the exception information.
    A simple try-catch example:

    <?php
    //create function with an exception
    function checkNum($number)
    {
    if($number<1)
    {
    throw new Exception(“Number must be greater than 0″);
    }
    return true;
    }
    //trigger exception in a “try” block
    try
    {
    checkNum(2);
    //If the exception is thrown, this text will not be shown
    echo ‘The number is greater than 0′;
    }
    //catch exception
    catch(Exception $e)
    {
    echo ‘Message: ‘ .$e->getMessage();
    }
    ?>

    Error Output:

    Message: Number must be greater than 0

The code above throws an exception and catches it.It works as follows:

  • The checkNum() function is created. It checks if a number is less than 1. If it is, an exception is thrown
  • The checkNum() function is called in a “try” block
  • The exception within the checkNum() function is thrown
  • The “catch” block retrives the exception and creates an object ($e) containing the exception information
  • The error message from the exception is echoed by calling $e->getMessage() from the exception object

PHP Exception Handling

Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008

0

Exceptions are special conditions which occur during execution and change the normal flow of a code.

These exceptions need to be handled to let the program going on.

PHP 5 provides an object oriented way of dealing with errors.

During the execution of a program some condition may appear when the program flow is need to be changed to protect the code from crashing or producing wrong results or stopping in the middle of execution. This is called Exception handling. And exceptions are the condtions which may cause any of the above situations.

When an exception occurs the following steps are executed:

  • The current code state is saved
  • The code execution will switch to a predefined (custom) exception handler function
  • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

Basic Idea for an Exception to handle is:

  • decide whether the Error produced needs to be handled and how
  • which exception to handle at which level and which point of tim
  • your code should keep running even if a severe (non-fatal) error occurs
  • make sure all errors of all the different types are handled uniformly.

Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

When an exception is thrown, the execution of the following code block is stopped, and PHP will try to find the code for catching the exception.

If an exception is not caught, a fatal error will be issued with an “Uncaught Exception” message.

PHP 5 handles exceptions in a similar way to that of other programming languages.

Exception handling introduces some new keywords as:

  • Try - It encloses the block of code or the function which is doubted to produce an exception. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is thrown automatically.
  • Throw – Throw lets you trigger an error manually.
  • Catch – It contains the code to handle the exceptions. A “catch” block retrieves an exception and creates an object containing the exception information.

When an exception is thrown, the program execution will be paused to handle the error. PHP will then attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception”

  • Each try must have at least one corresponding catch block.
  • Multiple catch blocks can be used to catch different classes of exceptions.
  • Exceptions can be thrown (or re-thrown) within a catch block also.

Lets try to throw an exception without catching it:

    <?php         //create function with an exception
    function checkNum($number)
    {
    if($number==0)
    {
    throw new Exception(“Value must not be 0″);
    }
    return true;
    }
    //trigger exception
    checkNum(0);
    ?>
    Output:

    Fatal error: Uncaught exception ‘Exception’
    with message ‘Value must not be 0′ in C:\wapplications\PHPprog.php:6
    Stack trace: #0 C:\wapplications\PHPprog.php(12):
    checkNum(28) #1 {main} thrown in C:\wapplications\PHPprog.php on line

PHP Error Logging

Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008

0

PHP sends an error log to the servers logging system or a file, depending on the error_log configuration in the php.ini file. But this can be changed using the error_log() function, ie you caqn send error logs to a file or a remote destination, specified by you.

You can also send error messages to yourself by e-mail. This is a good way of getting notified of specific errors.

Send an Error Message by E-Mail

In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:

    <?php //error handler function
    function customError($errorNo, $errorStr)
    {
    echo “<b>Error:</b> [$errorNo] $errorStr<br />”;
    echo “Webmaster has been notified”;
    error_log(“Error: [$errorNo] $errstr”,1,
    “user1@example.com”,”From: tutor@goweb99.com”);
    }
    //set error handler
    set_error_handler(“customError”,E_USER_WARNING);
    //trigger error
    $test=2;
    if ($test>1)
    {
    trigger_error(“Value must be 1 or below”,E_USER_WARNING);
    }
    ?>
    Output:

    Error: [512] Value must be 1 or below
    Webmaster has been notified

And the mail received from the code above looks like this:

    Error: [512] Value must be 1 or below

Custom Errors & Error Triggers

Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008

0

Creating a Custom Error Handler

A Custom Error Handler is a special function which is called when an error occurs in PHP.

This function should accept at least two parameters, ie error level and error message and at the max it may accept up to five parameters ie file, line-number, and the error context:

Syntax

    error_function(error_level,error_message,error_file,error_line,error_context)
    Parameter Description

    error_level

    Required. Specifies the error report level for the user-defined error. Must be a value number.
    error_message Required. Specifies the error message for the user-defined error
    error_file Optional. Specifies the filename in which the error occurred
    error_line Optional. Specifies the line number in which the error occurred
    error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred

These error report levels are the different types of error the user-defined error handler can be used for:

Error Report levels

    Value Constant Description
    2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
    8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
    256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
    512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
    1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
    4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
    8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

Now lets create a function to handle errors:

    function customError($errno, $errstr)
    {
    echo “<b>Error:</b> [$errno] $errstr<br />”;
    echo “Ending Script”;
    die();
    }

The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
Here we have created an error handling function, so mow we we need to decide when it should be triggered.

Set Error Handler

PHP provides a built in default error handler error handler.

You can also change the error handler to apply for only some errors, so this way you can make more handlers for different type of errors, which will handle the errors in specific ways.

    set_error_handler(“customError”);

Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.

Testing the error handler by trying to output variable that does not exist:

    For eg:

    <?php       //error handler function
    function customError($errno, $errstr)
    {
    echo “<b>Error:</b> [$errno] $errstr”;
    }
    //set error handler
    set_error_handler(“customError”);

    //trigger error
    echo($test);
    ?>

    Output:

    Error: [8] Undefined variable: test

Trigger an Error

In the above example we triggered the error without any reason. We need some valid trigger for the error handler to be triggered. When a user inputs data, some wrong input may be provided so we need to trigger the handler whenever a user inputs a invalid data. In PHP, this is done by the trigger_error() function.

In this example an error occurs if the “test” variable is bigger than “1″:

    For eg:

    <?php
    $test=2;
    if ($test>1)
    {
    trigger_error(“Value must be 1 or below”);
    }
    ?>

    Output:

    Note: Value must be 1 or below in C:\webfolder\test.php on line 6

By this method you can trigger an error anywhere you wish in a script. By adding a second parameter, you can specify what error level is triggered.

Possible error types:

  • E_USER_ERROR – Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
  • E_USER_WARNING – Non-fatal user-generated run-time warning. Execution of the script is not halted
  • E_USER_NOTICE – Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally

In this example an E_USER_WARNING occurs if the “test” variable is bigger than “1″. If an E_USER_WARNING occurs we will use our custom error handler and end the script:

    For eg:

    <?php          //error handler function
    function customError($errno, $errstr)
    {
    echo “<b>Error:</b> [$errno] $errstr<br />”;
    echo “Ending Script”;
    die();
    }
    //set error handler
    set_error_handler(“customError”,E_USER_WARNING);

    //trigger error
    $test=2;
    if ($test>1)
    {
    trigger_error(“Value must be 1 or below”,E_USER_WARNING);
    }
    ?>

    Output:

    Error: [512] Value must be 1 or below  Ending Script

PHP Error Handling- die() Statement

Posted by tutor | Posted in PHP Tutorial | Posted on 16-12-2009-05-2008

0

PHP provides a default error handling, which is very simple. An error message is sent to the browser, with filename, line number and a message describing the error.

Error handling is a vital part while working with scripts and creating web applications.

Error checking and handling helps you handle the errors your way, ie you can do what you want to do in case an error occurs. It makes your code look more professional and also provides security.

This tutorial contains some of the most common error checking methods in PHP.

Some of the most common error checking methods of PHP are:

  • Simple “die()” statements
  • Custom errors and error triggers
  • Error reporting

Using the die() function

The first example shows a simple script that opens a text file:

    <?php
    $file=fopen(“welcome.txt”,”r”);
    ?>
    Error Output if the file does not exist:

    Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:No such file or directory in C:\webfolder\test.php on line 2

You can avoid this situation by simple methods. First look for the file if it exists, then open it and if not then you can use the die() function.

    <?php
    if(!file_exists(“welcome.txt”))
    {
    die(“File not found”);
    }
    else
    {
    $file=fopen(“welcome.txt”,”r”);
    }
    ?>
    Error Output if the file does not exist:

    File not found

The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.

PHP E-mail Injections & Stopping Them

Posted by tutor | Posted in PHP Tutorial | Posted on 16-12-2009-05-2008

0

First, look at the PHP code from the previous chapter:

    <html>
    <body>
    <?php
    if (isset($_REQUEST['email']))   //if “email” is filled out, send email
    {
    $email = $_REQUEST['email'] ;
    $subject = $_REQUEST['subject'] ;
    $message = $_REQUEST['message'] ;
    mail(“someone@example.com”, “Subject: $subject”,
    $message, “From: $email” );
    echo “Thank you for using our mail form”;
    }
    else      //if “email” is not filled out, display the form
    {
    echo “<form method=’post’ action=’mailform.php’>
    Email: <input name=’email’ type=’text’ /><br />
    Subject: <input name=’subject’ type=’text’ /><br />
    Message:<br />
    <textarea name=’message’ rows=’15′ cols=’40′>
    </textarea><br />
    <input type=’submit’ />
    </form>”;
    }
    ?>
    </body>
    </html>

The problem with the code above is that unauthorized users can insert data into the mail headers via the input form.
Now suppose a if a user adds the following text to the email input field in the form

    someone@example.com%0ACc:person2@example.com
    %0ABcc:person3@example.com,person3@example.com,
    anotherperson4@example.com,person5@example.com
    %0ABTo:person6@example.com

The mail() function puts the text above into the mail headers as usual, and now the header has an extra Cc:, Bcc:, and To: field. When the user clicks the submit button, the e-mail will be sent to all of the addresses above!

PHP Stopping E-mail Injections

The best way to stop such e-mail injections is to validate the input.
In the code below we have added an input validator that checks the email field in the form:

    <html>
    <body>
    <?php
    function spamcheck($field)
    {
    //filter_var() sanitizes the e-mail address using FILTER_SANITIZE_EMAIL
    $field=filter_var($field, FILTER_SANITIZE_EMAIL);
    //filter_var() validates the e-mail address using FILTER_VALIDATE_EMAIL
    if(filter_var($field, FILTER_VALIDATE_EMAIL))
    {
    return TRUE;
    }
    else
    {
    return FALSE;
    }
    }
    if (isset($_REQUEST['email']))    //if “email” is filled out, proceed
    {
    $mailcheck = spamcheck($_REQUEST['email']);   //check if the email address is invalid
    if ($mailcheck==FALSE)
    {
    echo “Invalid input”;
    }
    else    //send email
    {
    $email = $_REQUEST['email'] ;
    $subject = $_REQUEST['subject'] ;
    $message = $_REQUEST['message'] ;
    mail(“someone@example.com”, “Subject: $subject”,
    $message, “From: $email” );
    echo “Thank you for using our mail form”;
    }
    }
    else     //if “email” is not filled out, display the form
    {
    echo “<form method=’post’ action=’mailform.php’>
    Email: <input name=’email’ type=’text’ /><br />
    Subject: <input name=’subject’ type=’text’ /><br />
    Message:<br />
    <textarea name=’message’ rows=’15′ cols=’40′>
    </textarea><br />
    <input type=’submit’ />
    </form>”;
    }
    ?>
    </body>
    </html>

These are the PHP filters that we used in the above code to validate input:

    The FILTER_SANITIZE_EMAIL- removes all illegal e-mail characters from a string
    The FILTER_VALIDATE_EMAIL- validates value as an e-mail address

PHP Sending E-mails

Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008

0

PHP allows you to send e-mails directly from a script.

The PHP mail() Function
The PHP mail() function is used to send emails from inside a script.

Syntax

    mail(to,subject,message,headers,parameters)
    Parameter Description
    to Required. Specifies the receiver / receivers of the email
    subject Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
    message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
    headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
    parameters Optional. Specifies an additional parameter to the sendmail program

But before you will be able to use mail functions, you should have a working email system. The program to be used is defined by the configuration settings in the php.ini file.

PHP Simple E-Mail

In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail:

    $to = "user1@example.com";
    $subject = "Sample mail";
    $message = "This is a test email message.";
    $from = "user2@example.com";
    $headers = "From: $from";
    mail($to,$subject,$message,$headers);
    echo "Mail Sent.";
    ?>