Класс капчи

602
.
Folour
Think different
Писал несколько месяцев назад для себя, но решил поделится.
<?php

/**
 * @author    Folour aka XeOn (SkyFire)
 * @project   FoEngine
 * @contacts  ICQ: 2666440, MAIL: Folour@i.ua
 * @copyright Folour Technologies, (c) 2012
 */
class Captcha {

    /**
     * @var array
     */
    protected $codeArr = array ();
    /**
     * @var int
     */
    protected $width = 80;
    /**
     * @var int
     */
    protected $height = 20;

    /**
     *
     */
    function __construct() {
        $arr = array_merge(array_diff(range('a', 'z'), array ('w', 'm', 'o', 'v', 'k')), range(3, 8));
        $length = rand(4, 6);
        $x = 1;
        while ($x <= $length) {
            $symbol = $arr[ array_rand($arr) ];
            $this->codeArr[ ] = $symbol;
            $x++;
        }
    }

    /**
     * @return bool|null
     */
    public function check() {
        if ($_SESSION[ 'captcha' ] == mb_strtolower($_POST[ 'captcha' ])) return TRUE;

        return NULL;
    }

    function genImage() {
        $image = imageCreateTrueColor($this->width, $this->height);
        $bgColor = imageColorAllocate($image, rand(220, 255), rand(220, 255), rand(220, 255));
        imagefilltoborder($image, $this->width, $this->height, 1, $bgColor);
        $i = rand(0, 5);
        foreach ($this->codeArr as $val) {
            $textColor = imagecolorallocate($image, rand(50, 180), rand(50, 180), rand(50, 180));
            if ($i < 20) imageline($image, rand(0, $this->width), rand(10, $this->height), rand(0, $this->width), rand(0, $this->height), $textColor);
            imagettftext($image, 13, 0, $i, ($this->height + 10) / 2, $textColor, ROOT . 'static/captcha/fonts/1.ttf', $val);
            $i += 13;
        }
        header('Content-type: image/gif');
        imagegif($image);
        imagedestroy($image);
        $_SESSION[ 'captcha' ] = implode('', $this->codeArr);
    }
}


В 55 строчке смените путь к шрифту.
Использовать так:
//где нужно вывести капчу
//предположим что есть автозагрузка и класс лежит вместе с системными классами
$captcha = new Captcha();
$captcha->genImage();


Там где нужно проверить капчу

$captcha = new Captcha();
if($captcha->check()) {
    //действия если капча правильная
}
else {
    //выводим ошибку
}


Для работы метода check() поле для ввода капчи должно быть именовано как captcha и передаваться методом POST.
--------------------------------
Все буквы и цифры разноцветные, добавлены помехи, в виде линий, которые иногда имеют такой же цвет как и буква, что усложнит разбор роботом.
.
Think different
Шрифт
Прикрепленные файлы:
.
Think different
Скрин
Прикрепленные файлы:
.
Люблю чай, как панда любит бамбук!
Спасибо
.
Think different
В архиве сам класс
Прикрепленные файлы:
.
Блиносвёрт ?
Folour, молодец!
.
Think different
Спасибо)
.
.
В зип формате есть??
.
Think different
В зипе
Прикрепленные файлы:
Всего: 21