PHP
  Home arrow PHP arrow Page 4 - Developing a Captcha Application with ...
Dev Shed Forums 
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 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
VeriSign Whitepapers 
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

Developing a Captcha Application with an Image Generator Class with PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 8
    2007-10-03

    Table of Contents:
  • Developing a Captcha Application with an Image Generator Class with PHP 5
  • The complete definition of the image generator class
  • Defining the core structure of a noisy image application
  • Developing a basic noisy image generation system

  • 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Developing a Captcha Application with an Image Generator Class with PHP 5 - Developing a basic noisy image generation system


    (Page 4 of 4 )

    As I stated in the section that you just read, the best way to demonstrate how the two previously defined classes can be put to work together to implement a simple noisy image system is by developing an example where you can see how they function in tandem.

    So first I will list the complete source code corresponding to the two classes. Here it is:

    // define 'ImageGenerator' class

    class ImageGenerator{

      private $width=400;

      private $height=300;

      private $bgColor='0,0,0';

      private $textColor='255,255,255';

      private $inputString='Default Input String';

      private $bgImage=NULL;

      private $img;

    // initialize input arguments

    public function __construct($inputString='Default Input String'){

      if(strlen($inputString>255)){

       throw new Exception('Invalid length for input string.');

    }

      $this->inputString=$inputString;

    }

      public function setImageWidth($width=400){

       if(!is_int($width)&&$width>800){

        throw new Exception('Invalid width for image stream.');

    }

      $this->width=$width;

    }

      public function setImageHeight($height=300){

       if(!is_int($width)&&$height>600){

        throw new Exception('Invalid height for image stream.');

     }

    }

      public function setImageBgColor($bgColor='0,0,0'){

       if(!preg_match("/^d{1,3},d{1,3},d{1,3}$/",$bgColor)){

        throw new Exception('Invalid format for background color.');

    }

      $this->bgColor=$bgColor;

    }

      public function setImageTextColor($textColor='255,255,255'){

       if(!preg_match("/^d{1,3},d{1,3},d{1,3}$/",$textColor)){

        throw new Exception('Invalid format for text color.');

    }

      $this->textColor=$textColor;

    }

      public function setBgImage($bgImage='default.gif'){

       if(!file_exists($bgImage)){

        throw new Exception('Invalid background image.');

    }

      $this->bgImage=$bgImage;

    }

      public function setImageFont($font){

       if(!file_exists($font)){

        throw new Exception('Invalid image font.');

    }

      $this->font=$font;

    }

    // create image stream

      public function displayImageStream(){

    $this->img=$this->bgImage!=NULL?imagecreatefromgif($this-
    >bgImage):imagecreate($this->width,$this->height);

      $bgColor=explode(',',$this->bgColor);

      $textColor=explode(',',$this->textColor);

    // allocate background color on image stream

    imagecolorallocate($this->img,$bgColor[0],$bgColor[1],$bgColor
    [2]);

    // allocate text color on image stream

    $textColor=imagecolorallocate($this->img,$textColor[0],$textColor
    [1],$textColor[2]);

    // load font

    if(!imagestring($this->img,5,$this->width/2-strlen($this-
    >inputString)*5,$this->height/2-5,$this->inputString,$textColor)){

      throw new Exception('Error creating image text');

    }

      header("Content-type: image/gif");

    // display image

      imagegif($this->img);

    // free up memory

      imagedestroy($this->img);

     }

    }

    class RandomGenerator{

      private $length;

      private $chars="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

      public function __construct($length=4){

       if(!is_int($length)||$length<1){

        throw new Exception('Invalid length for random string.');

    }

      $this->length=$length;

    }

      public function getRandomValue(){

       $rndstr='';

        $maxvalue=strlen($this->chars)-1;

       for($i=0;$i<$this->length;$i++){

        $rndstr.=substr($this->chars,rand(0,$maxvalue),1);

    }

      return $rndstr;

     }

    }

    Now, take a look at the following code sample, which shows how to embed dynamically several four-digit random strings into a predefined image stream:

      try{

    // create new instance of 'RandomGenerator' class

      $rnd=new RandomGenerator();

    // create new instance of 'ImageGenerator' class

      $imgGen=new ImageGenerator($rnd->getRandomValue());

    // display image stream on the browser

      $imgGen->displayImageStream();

    }

      catch(Exception $e){

       echo $e->getMessage();

      exit();

    }

     

    There you have it! By using the pair of PHP 5 classes that I built previously, it was feasible to develop a fully-functional noisy image application, which can be easily incorporated into any existing web site to prevent (at least partially) automated submissions of its web forms.

    Final thoughts

    Unfortunately, this series has come to and end. Hopefully the whole learning experience has been positive, since you learned how to utilize the functionality provided by some of the most important functions packaged with the GD extension to build an image generator class. As you have seen, such a class can be really handy for creating, among other useful things, a simple and efficient noisy image system.

    See you in the next PHP development tutorial!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · In this final installment of the series, the image generator class built in previous...
       · In the ImageGenerator constructor, the following...
       · Thank you commenting on my PHP article and for pointing out that small bug on the...
     

       

    PHP ARTICLES

    - Viewing and Editing Tasks for a Project Mana...
    - More on Private Methods with PHP 5 Member Vi...
    - Adding Tasks to a Project Management Applica...
    - Utilizing Private Methods with PHP 5 and Mem...
    - Making Changes in a Project Management Appli...
    - Defining Public and Protected Methods with M...
    - HTML for a Project Management Application
    - Using Subclasses and Accessors with Member V...
    - Implementing Internet Protocols with PHP
    - Project Management: The Application
    - Working with Private Properties to Protect P...
    - Protecting PHP 5 Class Data with Member Visi...
    - Setting Up a Web-based Image Hosting Service
    - Comparing Files and Databases with PHP Bench...
    - Setting Up a Web-Based Image Gallery





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway