Location: PHPKode > scripts > Easy CAPTCHA > captcha.php
<?php
/**
 * created : 10/08/2010
 * @author elmiloud chaabelasri <hide@address.com>
 *
 */

class Captcha {

	protected $_imageName  = 'captcha.jpeg';
	protected $_folderPath = './var/captcha';
	
	protected $_word;
	
	/**
	 * Return Path to captcha folder  
	 * @param void
	 * @return path
	 */
	public function getFolderPath (){
		return $this->_folderPath;
	}

	/**
	 * Return Path to captcha
	 * @param void
	 * @return patch
	 */
	public function getCaptchaPath(){
		return $this->_folderPath.'/'.$this->_imageName;
	}

	/**
	 * return Captcha URL
	 * @param void
	 * @return url
	 */
	public function getUrlCaptcha(){
		return $this->_folderPath.'/'.$this->_imageName;
	}

	/**
	 * Return word to show in captcha image
	 * @param void
	 * @return string ( 6 )
	 */
	public function getWord(){
		if(  ! $this->_word ){
			$RandomStr = md5(microtime());
			$this->_word = substr($RandomStr,0,6);
		}
		return $this->_word;
	}

	/**
	 * Check key captcha
	 * @param $key string
	 * @return bool
	 */
	public function check( $key ){
		return $_SESSION['captcha'] == $key ; 
	} 
	
	/**
	 * Main method to create captcha image and storage word in session
	 * @return unknown_type
	 */
	public function createCaptcha(){
		try {
			// Create a new folder in media folder
			$this->createDir( $this->getFolderPath() );
	
			// Delete old captcha
			if(  is_file( $this->getCaptchaPath() ) )
			unlink ( $this->getCaptchaPath() );
	
			// Get background image
			$NewImage =imagecreatefromjpeg( $this->getFolderPath().'/bg-captcha.jpg' );
	
			// Line color
			$LineColor = imagecolorallocate($NewImage,233,239,239);
	
			// Text color
			$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
	
			// Lines
			imageline($NewImage,1,1,40,40,$LineColor);
			imageline($NewImage,1,100,60,0,$LineColor);
	
			// Draw text
			imagestring($NewImage, 7, 20, 10, $this->getWord() , $TextColor);  
	
			// Save in session
		    $_SESSION['captcha'] = $this->getWord();
	
			// Create captcha image
			imagejpeg($NewImage, $this->getCaptchaPath()  );
		}catch( Exception $e ){
			echo $e->getMessage();
		}
	}

	/**
	 * Create dir
	 * @param $dir
	 * @return bool
	 */
	protected function createDir( $dir ) {
		if (! is_dir ( $dir )) {
			if (! mkdir ( $dir, 0755, true )) {
				throw new Exception(' Error when create folders ');
				return false;
			}
		}
		return true;
	}


}
Return current item: Easy CAPTCHA