Easy PHP Captcha

Costas

Administrator
Staff member
This class can generate images for user CAPTCHA validation.

It can generate a random alphanumeric text of random length between 4 and 8 characters for CAPTCHA validation.

The class can also generate a JPEG image with the random validation text displayed in it. The generated image saved to a server file.

JavaScript:
//https://www.phpclasses.org/package/10210-PHP-Generate-images-for-user-CAPTCHA-validation.html

<?php

class EasyCaptcha {

    private $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    private $finalChar;

    public function generateString() {
        $size = rand(4, 8);
        // echo $size;
        $temp = "";
        for ($i = 0; $i < $size; $i++) {
            $temp.= $this->chars[rand(0, strlen($this->chars) - 1)];
        }
        $this->finalChar = $temp;
        return $this->finalChar;
    }

    public function generateImage($urlImage=null) {
        $im = imagecreatetruecolor(120, 40);
        $val = (string) $this->finalChar;
        $text_color = imagecolorallocate($im, 255, 255, 255);
        imagestring($im, 15, 15, 15, $val, $text_color);
		if($urlImage == null){
			imagejpeg($im, 'captcha.jpg', 100);
			imagedestroy($im);
			echo "<img src='captcha.jpg']";	
		}
		else{
			imagejpeg($im, $urlImage.'captcha.jpg', 100);
			imagedestroy($im);
			echo "<img src='".$urlImage."captcha.jpg']";
			//  assets/uploadimg/captcha.jpg  ---- example of url
		}
        
    }

}

/* way to use */
  //  assets/uploadimg/captcha.jpg  ---- example of url
/*   session_start();
  $obj = new EasyCaptcha();
  $_SESSION["captcha"] =$obj->generateString();
  $obj->generateImage();
  echo $_SESSION["captcha"]; */
  
  
?>
 
Top