Here is the php code of generating captcha image. Enjoy it.
class GenerateCaptcha
{
protected $ImageName = 'captcha.jpeg'; // Background Image
protected $Path = './ImageFolder/captcha';
protected $CaptchWord;
public function getFolderPath ()
{
return $this->Path;
}
public function getCaptchaPath()
{
return $this->Path.'/'.$this->ImageName;
}
public function getUrlCaptcha()
{
return $this->Path.'/'.$this->ImageName;
}
public function getWord()
{
if(!$this->CaptchWord)
{
$RandomStr = md5(microtime());
$this->CaptchWord = substr($RandomStr,0,6);
}
return $this->CaptchWord;
}
public function check($key)
{
return $_SESSION['captcha'] == $key ;
}
public function createCaptcha()
{
try
{
$this->createDir($this->getFolderPath());
if(is_file( $this->getCaptchaPath()))
{
unlink ( $this->getCaptchaPath());
}
$NewImage =imagecreatefromjpeg($this->getFolderPath().'/bg-captcha.jpg');//Background Image For Captcha
$LineColor = imagecolorallocate($NewImage,233,239,239);
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
imageline($NewImage,1,1,40,40,$LineColor);
imageline($NewImage,1,100,60,0,$LineColor);
imagestring($NewImage, 7, 20, 10, $this->getWord() , $TextColor);
$_SESSION['captcha'] = $this->getWord();
imagejpeg($NewImage, $this->getCaptchaPath());
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
protected function createDir($dir)
{
if(!is_dir($dir))
{
if(!mkdir($dir, 0755, true))
{
throw new Exception(' Error when create folders ');
return false;
}
}
return true;
}
}
No comments:
Post a Comment