Example code Captcha with PHP and GD Library






In this tutorial I’ll teach you how to make a captcha with php using GD Graphics Library.

captcha

See live example clicking here

To create our captcha we will need: captcha.php index.php and arial.ttf (font)

Step 1 – captcha.php

<?php
session_start();
header("Content-type: image/jpeg");
$code = generateCode();
$fonts = str_split($code);
$img = imagecreatetruecolor(300,120);
$color=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
imagefill($img,0,0,$color);
$fontColor=imagecolorallocate($img,255,255,255);
$font ="arial.ttf";

for($i=0;$i<sizeof($fonts);$i++){
imagefttext($img,30,rand(-20,15),12*$i*2+35,45,$fontColor,$font,$fonts[$i]);
}

imagejpeg($img);
imagedestroy($img);
$_SESSION['captcha']=$code;

function generateCode(){
$cod1 = "";
$i = 0;

while($i<2){
$cod1.=chr(rand(48,57));;
$cod1.=chr(rand(65,90));;
$cod1.=chr(rand(97,122));;
$i++;
}
return $cod1;
}
?>

In this file we create an image with some letters, numbers and color random. In the session we keep the code that is displayed.

Step 2 – index.php

<?php
session_start();
$captcha= $_SESSION['captcha'];
?>

<img src='captcha.php'/>
<form action='index.php' method='POST'>
Captcha: <input type='text' name='captchaValue'/> <input type='submit' value='Check captcha'/>
</form>

<?php
$captchaValue=$_POST['captchaValue'];
if(isset($captchaValue)){

if(strtolower($captchaValue)==strtolower($captcha)){
echo "Valid captcha";
}else{
echo "Invalid captcha";
}
}
?>

In this file we show the image and check if the code is valid or invalid.

You can download all the files (with the font) clicking here




 
Leave a Comment
Your comment: