
V tomto mini howto sa snažím ukázať akým štýlom je tvorený captcha obrázok, teda obrázok používajúci sa k overeniu prispievateľa. Script je možné si samozrejme stiahnuť a voľne využívať na svojej stránke a ďalej upravovať. Tak pustime sa na do toho.
1. Krok - teória
Čo teda potrebujeme?
- Vytvoriť obrázok pomocou GD knižnice v PHP
- Daný kód preniesť medzi scriptami, teda miestom odoslania a miestom spracovania - na to použijeme SESSION premenné
- Overenie, to zvládne každý kto s PHP robí aspoň deň
2. Krok - kód
(nejdem veľa písať, väčšina kódu je popísaná priamo v scripte)
session_start();
class captcha{
// similiar looking characters have been removed / podobne znaky boli odstranene
var $availible = "23456789abcdefghjkmnpqrstuvwxyz";
function captcha($length,$width,$height){
$this->length=$length;
$code=$this->generate_code();
$image = @imagecreate($width,$height) or die('Error while creating image');
$this->image = $image;
//set background color / nastavi farbu pozadia
$background_color = imagecolorallocate($image, 255, 255, 255);
// background characters / znaky na pozadi
while ($i<10){
imagettftext($image, rand(13,20), rand(0,45), rand(0, $width), rand(0, $height), $this->text_color_random("light"), "GeosansLight.ttf" , substr($this->availible,rand(0,strlen($this->availible)),1)) or die('Error in imagettftext function');
$i++;
}
// horizontal lines / horizontalne ciary
for($i=0;$i<$height;$i=$i+10){
imageline($image, 0, $i, $width, $i, $this->text_color_random("light"));
}
// vertical lines / vertikalne ciary
for($i=0;$i<$width;$i=$i+10){
imageline($image, $i, 0, $i, $height, $this->text_color_random("light"));
}
// writing a code / vykreslenie kodu
while ($j<=$length){
imagettftext($image, 35, rand(-20,20), $j*$width/$length+10, $height/2+15, $this->text_color_random("dark"), "GeosansLight.ttf" , substr($code,$j,1) ) or die('Error in imagettftext function');
$j++;
}
// assign code to a session variable / pripoji kod do session premennej
$_SESSION[code]=$code;
//setting the content type / nastavenie typu
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
}
function generate_code(){
while ($i<$this->length){
$code .= substr($this->availible, mt_rand(0, strlen($this->availible)-1),1);
$i++;
}
return $code;
}
function text_color_random($mode){
if($mode=="light"){
$color = imagecolorallocate($this->image,rand(190,220),rand(190,220),rand(190,220));
}else{
$color = imagecolorallocate($this->image,rand(0,150),rand(0,150),rand(0,150));
}
return $color;
}
}
$length = $_GET[length] ? $_GET[length] : 6;
$width = $_GET[width] ? $_GET[width] : 200;
$height = $_GET[height] ? $_GET[height] : 70;
$image = new captcha($length,$width,$height);3. Krok - demo
Dúfam, že niekomu tento captcha kód pomôže :)