PHP
  Home arrow PHP arrow Page 2 - Error Handling in PHP: Coding Defensiv...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Error Handling in PHP: Coding Defensively
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 38
    2006-01-11

    Table of Contents:
  • Error Handling in PHP: Coding Defensively
  • Killing your scripts: basic error handling with the “die()” statement
  • Triggering errors: more efficient error handling with the “trigger_error()” function
  • The PEAR way: looking at the PEAR_Error object
  • True and false: handling errors with Boolean flags

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Error Handling in PHP: Coding Defensively - Killing your scripts: basic error handling with the “die()” statement


    (Page 2 of 5 )

    The first example that implements the basics of script-level error handling is based on the popular “die()” statement. For this reason, I’ll write a simple PHP class, which reads contents from a data file. In its basic incarnation, this class looks like this:

    class FileReader{
      var $file;
      var $fileDir='fileDir/';
      function FileReader($file){
        $this->file=$file;
      }
      function getContent(){
        return file_get_contents("{$this->fileDir}{$this->file}.php");
      }
    }

     

    As I mentioned earlier, the above class implements a trivial file reader. Aside from the constructor, the class exposes only one public method, “getContent()”, which reads the content from a file passed in as an argument to the constructor. As you can see, the class has been coded with no error checking lines, so any object instantiated from it will cause a non-fatal error if the “$file” parameter doesn’t point to a valid file. The lines below show this circumstance:

    // instantiate FileReader object
    // pass in invalid file to the constructor
    $fr=new FileReader('inexistent_file');
    // echo file content
    echo $fr->getContent();

    Warning: file_get_contents(fileDir/.php): failed to open stream: No such file or directory in /path/to/file/exceptions.php on line 4.

    Although the example is rather crude, it demonstrates in a nutshell how a class written without any error handler can be easily broken up. Now, in order to implement a basic error handler, I’m going to include some “die()” statements within the class methods, as follows:

    class FileReader{
      var $file;
      var $fileDir='fileDir/';
      function FileReader($file){
        if(!file_exists("{$this->fileDir}{$file}.php")){
          die('File '.$file.' not found');
        }
        $this->file=$file;
      }
      function getContent(){
        if(!$content=file_get_contents("{$this->fileDir}{$this->file}.php")){
          die("Unable to read file contents");
        }
        return $content;
      }
    }

     

    Now, the class looks subtly better and more efficient. Notice how a couple of “die()” statements allow you to code defensively, and introduce an appreciable difference compared to the earlier version. In this case, if I instantiate a new “file reader” object, by pointing it to an inexistent file, this is what I should get as a result:

    // instantiate FileReader object
    $fr=new FileReader('inexistent_file');
    // echo file content
    echo $fr->getContent();

    File inexistent_file not found.

    As you can see, the above snippet is a little more efficient, because it implements a simple error handling mechanism. Instead of leaving out of control conflictive operations, such as reading file contents, the class is capable at least of stopping program execution if an error occurs. Indeed, this is a considerable improvement from a programming point of view, and certainly didn’t demand any hard work from us.

    However, pseudo functions like “die()” statements are rather inflexible. After all, it doesn't always happen that a script must be abruptly terminated. Fortunately, PHP exposes other functions which are more helpful and flexible for handling errors. Considering this, let’s move on and have a look at the PHP built-in “trigger_error()” function, in order to find out how it can be used.

    More PHP Articles
    More By Alejandro Gervasio


       · This first article demonstrates some of the most common approaches for handling...
       · I had expected something about the try catch throw statements as well...Aren't...
       · Hello,Thank you for commenting on my article. Regarding your question, I covered...
       · Boolean flags are a technique I frequently use specifically in writing APIs. I...
       · Hello Lux,Thank you for your feedback on this article. I saw your method about...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT