digitorum.ru

Как меня найти

Профиль

icq: 4415944

Создаем изображение для captcha на php. chess captcha.

GD, captcha, php

Очередной пост из серии "how  to".

Будем делать примерно такое изображение:

Как будем усложнять жизнь ботам:

  • буквы под разными углами
  • буквы разного размера
  • нестандартные шрифты (скачать можно тут http://7fonts.r...)

Сразу хочу сказать, что капча блокирует не всех ботов, но  часть из них отсеивает. Да и вообще нет идеальной капчи.

<?php
	
	define('ROOT', '<['main.system.php.config'].documentRoot>');
	
	// исходные параметры изображения
	$captchaTextLength = 4;
	$captchaText = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $captchaTextLength);
	$captchaWidth = 200;
	$captchaHeight = 60;
	
	// создаем изображение
	$im = imagecreatetruecolor($captchaWidth, $captchaHeight);
	
	// цвета (рисовать будем черным и белым)
	$backgroungColor = imagecolorallocate($im, 255, 255, 255);
	$textColor = imagecolorallocate($im, 0, 0, 0);
	
	// какого цвета в итоге будет капча
	$colorize = array(82, 82, 82);
	
	// шрифт
	$fonts = array(
		ROOT . '/fonts/Mostwasted.ttf',
		ROOT . '/fonts/reasonsh.ttf',
		ROOT . '/fonts/DS-TERM.TTF'
	);
	
	// выбмраем рандомный шрифт из списка
	$font = $fonts[array_rand($fonts)];
	
	// заполняем изображение цветом фона
	imagefill($im, 0, 0, $backgroungColor);
	
	// наносим буквы
	$captchaText = preg_split("//", $captchaText, -1, PREG_SPLIT_NO_EMPTY);
	foreach($captchaText as $k => $letter) {
		$fontSize = rand($captchaHeight / 2, ceil($captchaHeight / 1.4));
		$fontAngle = rand(-45, 45);
		$fontX = (($k + 1) * $captchaWidth / ($captchaTextLength + 1));
		$fontY = $captchaHeight / 2 + $fontSize / 2 - rand(0, $captchaHeight / 4);
		imagettftext($im, $fontSize, $fontAngle, $fontX, $fontY, $textColor, $font, $letter);
	}
	
	// делим картинку на кусочки
	$pieceWidth = $captchaWidth / 8;
	$pieceHeight = $captchaHeight/ 2;
	for($i = 0; $i < $captchaWidth / $pieceWidth; ++$i) {
		for($j = 0; $j < $captchaHeight / $pieceHeight; ++$j) {
			if(($i % 2 == 0 && $j % 2 == 0) || ($i % 2 == 1 && $j % 2 == 1)) {
				// для получения темной клетки инвертуруем цвета
				$w = ceil($i * $pieceWidth);
				$h = ceil($j * $pieceHeight);
				$imPiece = imagecreatetruecolor($pieceWidth, $pieceHeight);
				imagecopy($imPiece, $im, 0, 0, $i * $pieceWidth, $j * $pieceHeight, $pieceWidth, $pieceHeight);
				imagefilter($imPiece, IMG_FILTER_NEGATE);
				imagecopy($im, $imPiece, $i * $pieceWidth, $j * $pieceHeight, 0, 0, $pieceWidth, $pieceHeight);
			}
		}
	}
	// колорируем изображение.
	imagefilter($im, IMG_FILTER_COLORIZE, $colorize[0], $colorize[1], $colorize[2]);
	header('Content-type: image/png');
	imagepng($im);
	
?>