Creating a simple CAPTCHA with PHP with made script.

Discussion in 'PHP' started by syeds, Apr 12, 2010.

  1. #1
    A CAPTCHA is a type of challenge-response test used in computing to determine whether the user is human. “CAPTCHA” is an acronym for “Completely Automated Public Turing test to tell Computers and Humans Apart”, trademarked by Carnegie Mellon University.

    Here is a small CAPTCHA class that will help you get rid of the nasty spam on your blog/forum/gallery. Written in PHP of course.

    class Captcha
    {
    	private $text;
     
    	/**
    	 * Class constructor and seed the random number generator
    	 *
    	 * @return Captcha
    	 */
    	public function __construct()
    	{
    		srand((double)microtime()*1000000^getmypid());
    	}
     
    	/**
    	 * Create the actual captcha image
    	 *
    	 * @param integer $width
    	 * @param integer $height
    	 * @return string
    	 */
    	public function Create_Image($width = 180, $height = 45)
    	{
    		header("Content-type:image/jpeg");
    		$img = imagecreate($width, $height);
    		$black = imagecolorallocate($img, 0, 0, 0);
    		$white = imagecolorallocate($img, 255, 255, 255);
    		$other = imagecolorallocate($img, 160, 160, 160);
    		$num = rand(0, 5);
    		for ($i = $num; $i < = $width; $i += 16)
    		{
    			imageline($img, $i, 0, $i, 45, $other);
    		}
    		for ($i = $num; $i <= $height + 10; $i += 16)
    		{
    			imageline($img, 0, $i, 180, $i, $other);
    		}
    		$string = substr(strtolower(md5(uniqid(rand(), 1))), 0, 7);
    		$string = str_replace('0', 'x', $string);
    		$font = imageloadfont('some_font.gdf');
    		imagestring($img, $font, 10, 8, $string, $white);
    		imagejpeg($img);
    		imagedestroy($img);
    		return $this->text = $string;
    	}
    }
    PHP:
    And, you use it with:
    
    require('Captcha.php');
    session_start();
    $CP = &new Captcha;
    $_SESSION['captcha'] = $CP->Create_Image();
    PHP:
     
    Last edited: Apr 12, 2010
    syeds, Apr 12, 2010 IP
  2. skywebsol

    skywebsol Well-Known Member

    Messages:
    161
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    103
    #2
    hmm new member thanks man
     
    skywebsol, Apr 12, 2010 IP
  3. zeustek

    zeustek Well-Known Member

    Messages:
    155
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #3
    thanks for sharing
     
    zeustek, Apr 13, 2010 IP
  4. alberrambo

    alberrambo Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    this is not working
     
    alberrambo, Apr 14, 2010 IP