Более надежней крч
---Класс captcha----
<?php
class Captcha{
protected static $code='';
protected static $doc='';
function Captcha(){
self::$doc=$_SERVER['DOCUMENT_ROOT'];
if(!is_dir(self::$doc.'/tmp/')){
mkdir(self::$doc.'/tmp',0755);
}
self::$code=self::gen();
}
function gen($length = 4) { $chars = 'QWERTYUIOPASDFGHJKLZXCVBNM0123456789'; $count = mb_strlen($chars); for ($i = 0, $result = ''; $i < $length; $i++) { $index = rand(0, $count - 1); $result .= mb_substr($chars, $index, 1); } return $result; }
function input(){
if(isset($_COOKIE['cpt'])){
self::clear();
}
$tmp=sha1(time());
$fp=fopen(self::$doc.'/tmp/'.$tmp. '_captcha.cache','w');
fwrite($fp,self::$code);
fclose($fp);
setcookie('cpt',$tmp,time()+60*5,'/');
return '<img src="/cimg.php?sid='.$tmp.'"><br/>Проверочный код:<br/><input type="text" name="captcha" value="" placeholder=" Введите код с картинки..."><br/>';
}
public static function image(){
header('Content-Type: image/png');
$im=imagecreatetruecolor(400,30);
$white=imagecolorallocate($im,255,255,255);
$grey=imagecolorallocate($im,128,128,128);
$black=imagecolorallocate($im,0,0,0);
imagefilledrectangle($im,0,0,399,29,$white);
$text=file_get_contents($_SERVER['DOCUMENT_ROOT'].'/tmp/'.$_GET['sid'].'_captcha.cache');
$font='9923.ttf';
//$text='test';
imagettftext($im,20,0,11,21,$grey,$font,$text);
imagettftext($im,20,0,10,20,$black,$font,$text);
imagepng($im);
imagedestroy($im);}
function check(){
$tcode=file_get_contents(self::$doc.'/tmp/'.$_COOKIE['cpt'].'_captcha.cache');
$code=$_POST['captcha'];
return ($code==$tcode);
self::clear();
}
function bug(){
$tcode=file_get_contents(self::$doc.'/tmp/'.$_COOKIE['cpt'].'_captcha.cache');
$code=$_POST['captcha'];
echo $tcode.' | '.$code;
}
function clear(){
return unlink(self::$doc.'/tmp/'.$_COOKIE['cpt'].'_captcha.cache');
setcookie('cpt','',time()-1,'/');
}
}//class
?>
-----Файл cimg.php -----
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/captcha.php';
Captcha::image();
?>
--------Пример------
<?php
include 'captcha.php';
$cpt=new Captcha();
If(!$cpt->check()){
//Error
}Else{
//Good
}
?>
<Form method="post">
<?=$cpt->input();?>
<Input type="submit" value="ok"></form>