неОпытный
   
Профиль
Группа: Модератор
Сообщений: 9820
Регистрация: 18.5.2006
Где: Днепропетровск
Репутация: 3 Всего: 260
|
Итак, данный FAQ посвящен созданию собственной CAPTCHA. Кто не знает что это такой, прощу сюда - http://ru.wikipedia.org/wiki/CaptchaЗа основу был взят этот класс - http://forum.vingrad.ru/forum/topic-188579.htmlЯ его немного доработал. Класс расчитан на то что у вас на сервере установлен PHP 5. Для начала создадим файл, например Captcha.Class.php. Копи-пастим туда написанный мною код: Код | <?
/* +-------------------------------------------------------------------------- | Captcha | ======================================== | by Daniil R | (c) 2004 - 2007 Zona Team | Captcha if free software. ^____^ +--------------------------------------------------------------------------- | > $Date: 21:00 ( 23.12.2007 ) | > $Author: Dan aka gta4kv $ +--------------------------------------------------------------------------- */
class Image { var $image, $text, $width, $height, $font, $ColorRand, $ColorRandAlpha; /** * Do image. * * @param integer $width * @param integer $height */ public function addImage( $width = "120", $height = "50" ) { if( !is_numeric( $width ) ) $width = 120; if( !is_numeric( $height ) ) $height = 50; $this->width = $width; $this->height = $height; $this -> image = imagecreate( $width, $height ); $colorBody = imagecolorallocatealpha($this -> image, rand( 0,40 ), rand( 40, 80 ), rand( 80, 120 ) , rand( 0,100 ) ); $colorShadow = imagecolorallocate($this -> image, 0x33, 0x33, 0x33); $colorHighlight = imagecolorallocate($this -> image, 0xCC, 0xCC, 0xCC); $colorRand = imagecolorallocate( $this->image, rand( 120, 160 ), rand( 160, 200 ), rand( 200,255 ) ); $this -> ColorRand = $colorRand; imagefilledrectangle( $this -> image, 1, 1, $width-2, $height-2, $colorBody ); } public function AddHendler( $name, $value ) { $this->$name = $value; } /** * Add bokder on the image. * */ public function addBorder() { if( $this -> image ) { $colorShadow = imagecolorallocate($this -> image, rand( 0, 255 ) , rand( 0, 255 ) , rand( 0, 255 ) ); $colorHighlight = imagecolorallocate($this -> image, rand( 0, 255 ) , rand( 0, 255 ) , rand( 0, 255 ) ); imageline( $this -> image, 0, $this->height-1, $this->width-1, $this->height-1, $colorShadow ); imageline( $this -> image, $this->width-1, 1, $this->width-1, $this->height-1, $colorShadow) ; imageline( $this -> image, 0, 0, $this->width-1, 0, $colorHighlight ); imageline( $this -> image, 0, 0, 0, $this->height-2, $colorHighlight ); } else { print 'Сначало надо создать картинку. ( $class -> new Button( "100", "30", $word, rand( 11, 13 ) ); ) '; exit; } } /** * Add text on the image. * * @param integer $alphavit * @param integer $font */ public function addText( $alphavit = "0", $font ) { if( $alphavit == 0 ) { $alphavit = 'qwertyuiopasdfghjklzxcvbnm'; } elseif ( $alphavit == 1 ) { $alphavit = '1234567890'; } else { $alphavit = 'qwertyuiopasdfghjklzxcvbnm1234567890'; }
for( $i = 0; $i<6; $i++) { $word .= $alphavit{ rand(0, strlen( $alphavit )-1 ) }; } $labelHeight = imagefontheight( $font ); $labelWidth = imagefontwidth( $font ) * strlen( $word ); $labeXrndNum = rand( 10, 20 ); $labelX = ( $this->width - $labelWidth ) / 2 - $labeXrndNum; $labelY = ( $this->height - $labelHeight ) / 2 + 15; $fonts = array( 'font1.otf', 'font2.ttf', 'font3.ttf', 'font5.ttf', ); $text = imagettftext( $this -> image, $font, rand(-5, 12), $labelX, $labelY, $this -> ColorRand, 'files/'.$fonts[ rand( 0, count( $fonts ) -1 ) ], $word ); $this -> text = $label; } /** * Add noise on captcha * * @param integer $count */ public function AddNoise( $count = "100" ) { if( !is_numeric( $count ) ) { $count = 100; } if( $this -> image ) { for( $i=0; $i<$count; $i++ ) { $Color = imagecolorallocate( $this -> image, rand( 0, 255 ), rand( 0, 255 ), rand( 0, 255 ) ); $x = rand( 0, imagesx( $this -> image ) ); $y = rand( 0, imagesy( $this -> image ) ); imageline( $this -> image, $x, $y, $x+1, $y+1, $Color ); } } } /** * Apply filter on the image. * * @param string $filter * @param integer $args * @return boolean */ public function AddFilter( $filter, $args = "" ) { $status = false; if( $args == "" ) { $args = 0; } if( $filter == "contrast" ) { if( $this -> image ) { $status = imagefilter( $this -> image, $filter, $args); // Changes the contrast of the image. } } if( $filter == "negate" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_NEGATE ); // Reverses all colors. } } if( $filter == "grayscale" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_GRAYSCALE ); // Converts the image into grayscale. } } if( $filter == "brightness" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_BRIGHTNESS, $args ); // Changes the brightness of the image. } } if( $filter == "edgedetect" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_EDGEDETECT ); // Uses edge detection to highlight the edges in the image. } } if( $filter == "emboss" ) { if( $this -> image ) { $status = imagefilter( $this -> image , IMG_FILTER_EMBOSS ); // Embosses the image. } } if( $filter == "gaussian_blur") { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_GAUSSIAN_BLUR ); // Blurs the image using the Gaussian method. } } if( $filter == "blur" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_SELECTIVE_BLUR ); // Blurs the image. } } if( $filter == "meanremoval" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_MEAN_REMOVAL ); } } if( $filter == "smooth" ) { if( $this -> image ) { $status = imagefilter( $this -> image, IMG_FILTER_SMOOTH, $args ); // Makes the image smoother. Use arg1 to set the level of smoothness. } } return $status; } public function draw() { if( !is_array( $this->imagetype ) ) { $ifunc = 'image'.$this->imagetype; if( !function_exists( $ifunc ) ) { header( 'Content-type: image/png' ); imagepng( $this -> image ); } else { header( 'Content-type: image/'.$this->imagetype ); $ifunc( $this->image ); } } else { if( $this->imagetype[0] != "jpeg" ) exit; $ifunc = 'image'.$this->imagetype[0]; if( !function_exists( $ifunc ) ) exit; header( 'Content-type: image/'.$this->imagetype[0] ); $ifunc( $this -> image, '', $this->imagetype[1] ); } } public function getCaptchaText() { return $this->text; } }
?>
|
Разберем основные функции: addImage - два параметра width и height, т.е ширина и высота. Функции создает картинку с заданными параметрами. Данный пример расчитан под 120х50. addBorder - параметров нет. Добавляет рамку к картинке. addText - два параметра alphavit и font. - alphavit - тип текста. 0 - только буквы, 1 - только цифры, 2 - цифры и буквы.
- font - размер шрифта на картинке. Данный пример расчитан под 18. ( максимум )
draw - параметров нет. Выводит картинку. Теперь создадим еще один файл, например index.php. Опять копи-пастим туда код: Код | <? /* +-------------------------------------------------------------------------- | Captcha | ======================================== | by Daniil R | (c) 2004 - 2007 Zona Team | Captcha if free software. ^____^ +--------------------------------------------------------------------------- | > $Date: 21:00 ( 23.12.2007 ) | > $Author: Dan aka gta4kv $ +--------------------------------------------------------------------------- */
session_start(); session_name('captcha');
require_once( 'Captcha.Class.php' ); $captcha = new Image(); $captcha->addImage( '120', '50' ); $captcha->addText( 2, rand( 17, 18 ) ); $captcha->addBorder(); $captcha->draw(); $_SESSION['captha_text'] = $captcha->getCaptchaText();
?>
|
Что здесь? О_о Отвечаю: Создаем класс, и картинку размером 120х50: Код | $captcha = new Image(); $captcha->addImage( '120', '50' );
|
Эти два действия обязательны. Добавим текст на картинку: Код | $captcha->addText( 2, rand( 17, 18 ) );
|
Это действия тоже обязательное. ( Что есть эти два параметра - вы можете прочитать выше ) Дальше добавим рамку: Код | $captcha->addBorder();
|
Это уже добавляется по желанию. Осталось только вывести картинку и записать в сессию то что было на картинке: Код | $captcha->draw();
$_SESSION['captha_text'] = $captcha->getCaptchaText();
|
Это самый простой пример создания CAPTCHA с помощью этого класса. Так же есть еще пара интересных функций: AddFilter - два параметра. filter и args. - - Название фильтра.
- - Нужное значение для его использования.
Вот список фильтров, возможно позже добавлю еще: - contrast - изменяет контраст картинки, обязательно указывать $args. Если не указано то значение устанавливается в 0.
- negate - делает негатив. ( искажает все цвета ), $args не используется.
- grayscale - конвертирует картинку в черно-белую, $args не используется.
- brightness - устанавливает контраст для картинки, обязательно указывать $args. Если не указано то значение устанавливается в 0.
- edgedetect - "выделяет края", $args не используется.
- emboss - незнаю как описать. попробуйте увидите. $args не используется.
- gaussian_blur и blur - размытие картинки. $args не используется.
- meanremoval- удаляет "поверхностный" эффект.
- smooth - типа blur. размытие картинки. обязательно указывать $args. Если не указано то значение устанавливается в 0.
Пример использования: Код | $captcha->AddFilter( 'edgedetect' );
|
Так же, если вы хотите указать формат картинки до использования функции draw() надо вписать такой код: Код | $captcha->AddHendler( 'imagetype', 'gif' );
|
Если не указывать, то будет выводиться в PNG. Если хотите использовать JPEG и при этом указать его качество строка должна выглядить так: Код | $captcha->AddHendler( 'imagetype', array( 'jpeg', 100 ) );
|
Где 100 - качество изображения. Так же не описал выше очень важный массив, а точнее массив $fonts в котором у нас хранятся названия наших шрифтов. Ибо CAPTCHA с одним шрифтом - это менее безопасно. В $fonts через запятую просто вбиваем названия шрифтов. ( должны лежать в папке files ) Функция AddNoise добавляет "мусор" на картинку. Один параметр count - кол-во "мусора". Пример использования CAPTCHA со всеми наворотами: Код | <? /* +-------------------------------------------------------------------------- | Captcha | ======================================== | by Daniil R | (c) 2004 - 2007 Zona Team | Captcha if free software. ^____^ +--------------------------------------------------------------------------- | > $Date: 21:00 ( 23.12.2007 ) | > $Author: Dan aka gta4kv $ +--------------------------------------------------------------------------- */
session_start(); session_name('captcha');
require_once( 'ZL.Captcha.Class.php' ); $captcha = new Image(); $captcha->AddHendler( 'imagetype', array( 'jpeg', 100 ) ); $captcha->addImage( '120', '50' ); $captcha->addText( 2, rand( 17, 18 ) ); $captcha->addBorder(); $captcha->AddFilter( 'smooth', 20 ); $captcha->AddFilter( 'meanremoval' ); $captcha->AddFilter( 'edgedetect' ); $captcha->AddFilter( 'brightness', rand( 0, 100 ) ); $captcha->AddNoise( '200' ); $captcha->draw();
$_SESSION['captha_text'] = $captcha->getCaptchaText();
?>
|
Всем спасибо за внимания! Исходники вместе со шрифтами приципляю в аттачь. Автор: gta4kv Источник: VingradЭто сообщение отредактировал(а) skyboy - 26.12.2007, 22:57
|