How to Generate Captcha Image using PHP

By | 14/11/2013

Captcha Image is required for most of the signup function or download links. With the captcha only we can detect is this a User or a Automated script. In PHP Captcha Image can be generated dynamically.Generate Captcha image Using PHP is too simple. No Extra Plugins Needed.

Arial font is needed, Otherwise captcha image generator in PHP won’t Work.

Download the Full Plugin at end of this Post.

form.php

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
@session_start();
if(isset($_POST['submit']))
{
if($_SESSION['captcha']==$_POST['text'])
{
echo "<script type="text/javascript">// <![CDATA[
alert('Correct Captcha');
// ]]></script>";
}
else
{
echo "<script type="text/javascript">// <![CDATA[
alert('In Correct Captcha');
// ]]></script>";
}
}
?>
<form name="captcha" action="" method="post">
<label>Enter your Text Here</label>
<input type="text" name="text"/>
<input type="submit" value="Click Here" name="submit"/>
</form>
<img src="captcha.php">

captcha.php

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
//Tobby News(www.tobbynews.com)
//created by Praveen
$font='arial.ttf';
$charset = '0123456789';
$code_length = 6;
$height = 30;
$width = 100;
@session_start();
$code = '';
for($i=0; $i < $code_length; $i++) {
$code = $code . substr($charset, mt_rand(0, strlen($charset) - 1), 1);
}
$font_size = $height * 0.7;
$image = @imagecreate($width, $height)or die("Cannot Initialize new GD image stream");
$background_color = @imagecolorallocate($image, 0, 0, 0);
/* render text */
$text_color = @imagecolorallocate($image, 20, 40, 100);
@imagettftext($image, $font_size, 0, 0,$font_size,$text_color, $font , $code)or die('Cannot render TTF text.');
//setting the page type to image
header('Content-Type: image/png');
@imagepng($image) or die('imagepng error!');
@imagedestroy($image);
// sending the captcha code to session
$_SESSION['captcha'] = $code;
exit();
?>

Here the simple demo for the Captcha image generation and validation.

Download the Full Plugin Here with Arial Font.

Post By Praveen (38 Posts)

Website: →

Connect

About Praveen

Praveen S has written 38 post in this blog.

Leave a Reply