Monday, June 30, 2014

PHP Error and try-catch Exception handling functions with sample code


PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed, and PHP will 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 ..." message, unless a handler has been defined with set_exception_handler().

In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

SPL provides a set of standard Exceptions.
See also the Predefined Exceptions

PHP - Validate Name, E-mail, and URL

php string validation preg_match Now, the script looks like this:


// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);


int preg_match (string pattern, string string [, array pattern_array],
                              [, int $flags [, int $offset]]]);

The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.

Using die() function:

While wirting your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Try following example without having /tmp/test.xt file and with this file.

 die("File not found");
 print "Opend file sucessfully";
 // Test of the code here.

This way you can write an efficient code. Using abive technique you can stop your program whenever it errors out and display more meaningful and user friendly meassage.

Defining Custom Error Handling Function:

You can write your own function to handling any error. PHP provides you a framwork to define error handling function.

This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):


error_function(error_level,error_message, error_file,error_line,error_context);

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

Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator

Fatal run-time errors. Execution of the script is halted
Non-fatal run-time errors. Execution of the script is not halted
Compile-time parse errors. Parse errors should only be generated by the parser.
Run-time notices. The script found something that might be an error, but could also happen when running a script normally
Fatal errors that occur during PHP's initial startup.
Non-fatal run-time errors. This occurs during PHP's initial startup.
Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

All the above error level can be set using following PHP built-in library function where level cab be any of the value defined in above table.

int error_reporting ( [int $level] )

Following is the way you can create one error handling function:

function handleError($errno, $errstr,$error_file,$error_line)
 echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
 echo "<br />";
 echo "Terminating PHP Script";

Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist.

error_reporting( E_ERROR );
function handleError($errno, $errstr,$error_file,$error_line)
 echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
 echo "<br />";
 echo "Terminating PHP Script";
//set error handler
//trigger error

Exceptions Handling:

PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.

Lets explain thre new keyword related to exceptions.

·         Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".

·         Throw - This is how you trigger an exception. Each "throw" must have at least one "catch".

·         Catch - - A "catch" block retrieves an exception and creates an object containing the exception information.

When an exception is thrown, code following the statement will not be executed, and PHP will 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 ...

·         An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block.

·         Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions.

·         Exceptions can be thrown (or re-thrown) within a catch block.


Following is the piece of code, copy and paste this code into a file and verify the result.

try {
    $error = 'Always throw this error';
    throw new Exception($error);
    // Code following an exception is not executed.
    echo 'Never executed';
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
// Continue execution
echo 'Hello World';

In the above example $e->getMessage function is uded to get error message. There are following functions which can be used from Exception class.

·         getMessage()- message of exception

·         getCode() - code of exception

·         getFile() - source filename

·         getLine() - source line

·         getTrace() - n array of the backtrace()

·         getTraceAsString() - formated string of trace

Creating Custom Exception Handler:

You can define your own custome excpetion handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )

Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().


function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
throw new Exception('Uncaught Exception');
echo "Not Executed\n";

Check complete set of error handling functions at PHP Error Handling Functions


PDO::PARAM_BOOL (integer)
Represents a boolean data type.
PDO::PARAM_NULL (integer)
Represents the SQL NULL data type.
PDO::PARAM_INT (integer)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer)
Represents the SQL large object data type.
PDO::PARAM_STMT (integer)
Represents a recordset type. Not currently supported by any drivers.
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.

<?php/* Execute a prepared statement by binding PHP variables */$calories 150;$colour 'red';$sth $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?'

filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

Sanitize filters 

List of filters for sanitization
FILTER_SANITIZE_EMAIL"email"Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
FILTER_SANITIZE_MAGIC_QUOTES"magic_quotes"Apply addslashes().
FILTER_SANITIZE_NUMBER_INT"number_int"Remove all characters except digits, plus and minus sign.
FILTER_SANITIZE_SPECIAL_CHARS"special_chars"FILTER_FLAG_STRIP_LOW,FILTER_FLAG_STRIP_HIGH,FILTER_FLAG_ENCODE_HIGHHTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
FILTER_SANITIZE_FULL_SPECIAL_CHARS"full_special_chars"FILTER_FLAG_NO_ENCODE_QUOTES,Equivalent to callinghtmlspecialchars() withENT_QUOTES set. Encoding quotes can be disabled by settingFILTER_FLAG_NO_ENCODE_QUOTES. Like htmlspecialchars(), this filter is aware of thedefault_charset and if a sequence of bytes is detected that makes up an invalid character in the current character set then the entire string is rejected resulting in a 0-length string. When using this filter as a default filter, see the warning below about setting the default flags to 0.
FILTER_SANITIZE_STRIPPED"stripped"Alias of "string" filter.
FILTER_SANITIZE_URL"url"Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.

how to redirect all the not found pages in to a common page using htaccess 
 Go to command prompt, cd to the appropriate folder and type:
notepad .htaccess
 After confirmation dialog the file will be created and you will be editing it directly. If you just want to create an empty file, try
echo. > .htaccess
orcreate the file by typing ".htaccess." in explorer, and the last dot will be removed automatically.

  1. Create a Web page that will be your 404 document.
  2. Open yourhttpd.conffile for editing (you'll probably have to login as root to edit it).
  3. Find the line that reads
    ErrorDocument 404 /404.html
  4. Change the third entry to the URI you would like to display, e.g.
    ErrorDocument 404 /new_404.html

(PHP 5 >= 5.1.0)
Exception::getCodeGets the Exception code

try {
throw new
Exception("Some error message", 30);
} catch(
Exception $e) {
"The exception code is: " . $e->getCode();

This document will explain how to create a .htaccess file to redirect your site or site content. This will not redirect any emails for your domains.
As a configuration file, .htaccess is very powerful. Even the slightest syntax error (like a missing space) can result in your content not displaying correctly or at all.
Since .htaccess is a hidden system file, please make sure your FTP client is configured to show hidden files. This is usually an option in the program's preferences/options.
This article is provided as a courtesy. Installing, configuring, and troubleshooting third-party applications is outside the scope of support provided by (mt) Media Temple. Please take a moment to review the Statement of Support.


1. Create an empty text file using a text editor such as notepad, and save it as htaccess.txt.
The reason you should save the file as htaccess.txt is because many operating systems and FTP applications are unable to read or view .htaccess files by default. Once uploaded to the server you can rename the file to .htaccess.
2. Edit the contents of the file. Check the following examples:
301 (Permanent) Redirect: Point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "" domain:
# This allows you to redirect your entire website to any other domain
Redirect 301 /

302 (Temporary) Redirect: Point an entire site to a different temporary URL. This is useful for SEO purposes when you have a temporary landing page and plan to switch back to your main landing page at a later date:
# This allows you to redirect your entire website to any other domain
Redirect 302 /

Redirect index.html to a specific subfolder:
# This allows you to redirect index.html to a specific subfolder
Redirect /index.html

Redirect an old file to a new file path:
# Redirect old file path to new file path
Redirect /olddirectory/oldfile.html
Redirect to a specific index page:
# Provide Specific Index Page (Set the default handler)
DirectoryIndex index.html

3. Upload this file and re-name it to .htaccess.
  • If using a text editor, be sure to save the file as plain text.
  • Paths to where you should save this file can be found in this article: System paths.
  • The definitive guide on Apache directives that can be used in .htaccess files can be found here:

More powerful URL changes with mod_rewrite

If you need to make complex changes to the way your URL displays, you should visit Using .htaccess rewrite rules. You can do things like add "www" to the beginning of your URL, redirect all requests to a subfolder but keep the rest of the URL, etc.

Here’s a very simple solution to handling a variety of HTTP errors like 404, 500.. etc in one php file. All we need to do is create an array of error codes and match against them by picking up the global redirect status code using PHP. This means that we can use one page the handle multiple errors.

The Code

You’ll need to update your .htaccess file so when an error is detected the server knows how to handle the request. In our case we’re going to forward all the listed errors to our generic errors.php file.

ErrorDocument 400 /errors.php

ErrorDocument 403 /errors.php

ErrorDocument 404 /errors.php

ErrorDocument 405 /errors.php

ErrorDocument 408 /errors.php

ErrorDocument 500 /errors.php

ErrorDocument 502 /errors.php

ErrorDocument 504 /errors.php


This is the contents of the ‘errors.php’ file. You need to save this in the root directory of your web server, unless you modify the path in the .htaccess file above.

$codes = array(
400 => array('400 Bad Request', 'The request cannot be fulfilled due to bad syntax.'),
403 => array('403 Forbidden', 'The server has refused to fulfil your request.'),
404 => array('404 Not Found', 'The page you requested was not found on this server.'),
405 => array('405 Method Not Allowed', 'The method specified in the request is not allowed for the specified resource.'),
408 => array('408 Request Timeout', 'Your browser failed to send a request in the time allowed by the server.'),
500 => array('500 Internal Server Error', 'The request was unsuccessful due to an unexpected condition encountered by the server.'),
502 => array('502 Bad Gateway', 'The server received an invalid response while trying to carry out the request.'),
504 => array('504 Gateway Timeout', 'The upstream server failed to send a request in the time allowed by the server.'),
$title = $codes[$status][0];
$message = $codes[$status][1];
if ($title == false || strlen($status) != 3) {
$message = 'Please supply a valid HTTP status code.';


PHP Try and Catch for SQL Insert

You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry

// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}

function my_mysql_query($query, $conn=false) {
    $res = mysql_query($query, $conn);
    if (!$res) {
        $errno = mysql_errno($conn);
        $error = mysql_error($conn);
        switch ($errno) {
            throw new MySQLDuplicateKeyException($error, $errno);
            throw MySQLException($error, $errno);
    // ...
    // doing something
    // ...
    if ($something_is_wrong) {
        throw new Exception("Logic exception while performing query result processing");


try {
    mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
catch (MySQLDuplicateKeyException $e) {
    // duplicate entry exception
catch (MySQLException $e) {
    // other mysql exception (not duplicate key entry)
catch (Exception $e) {
    // not a MySQL exception

Learn PHP MySQL from Call +94 777 33 7279 Skype ITClassSL

No comments:

Facebook Blogger Plugin: By

Post a Comment