How to generate a captcha using PHP
In this article, we’ll see how to generate a very simple and effective Captcha Image in PHP. Captchas are smart (at least most of the time) verification systems that prevent sites from bots that steals data from the site or unnecessarily increases the traffic of the site. In addition to preventing spams, Captchas are also used as a layer-of-protection against prevent DDoS attacks by malicious hackers.
So long-story-short Captchas are super-useful in this 21st Century. Captchas being so important nowadays (for security reasons mainly) should almost always be implemented in a server-side language like PHP and not client-sided JavaScript. The reason being that it becomes super-easy for any “robot” to bypass the security since the verification is done on the client-side (and it doesn’t even involve any image processing). So for that reason, we’ll make the Image Captcha in PHP using the GD (Graphics Draw) library which is usually installed by default.
Style.css
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333;
background-color: #FFF;
}
a {
-moz-user-select: none;
color: #1155CC !important;
font-family: "verdana", "Helvetica Neue", Helvetica, Arial, sans-serif;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
#frame1, #frame0 {
background-color: #F7F7F7;
margin: 30px auto auto;
padding: 10px;
width: 750px;
border: 1px solid #EEE;
}
#fade {
background: none repeat scroll 0 0 #D3DCE3;
display: none;
height: 100%;
left: 0;
opacity: 0.4;
position: fixed;
top: 0;
width: 100%;
z-index: 99;
}
#centerBox {
background-color: #FFFFFF;
border: 5px solid #FFFFFF;
border-radius: 2px 2px2px2px;
box-shadow: 0 1px 3px rgba(34, 25, 25, 0.4);
display: none;
max-height: 480px;
overflow: auto;
visibility: hidden;
width: 710px;
z-index: 100;
}
.box1 {
background: none repeat scroll 0 0 #F3F7FD;
border: 1px solid #D3E1F9;
font-size: 12px;
margin-top: 5px;
padding: 4px;
}
.button1 {
background-color: #FFFFFF;
background-image: -moz-linear-gradient(center bottom, #EDEDED 30%, #FFFFFF 83%);
border-color: #999999;
border-radius: 2px 2px2px2px;
border-style: solid;
border-width: 1px;
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
color: #333333;
cursor: pointer;
display: inline-block;
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
font-weight: 700;
height: 25px;
line-height: 24px;
margin-right: 2px;
min-width: 40px;
padding: 0 16px;
text-align: center;
text-decoration: none;
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
}
.button1:hover {
text-decoration: underline;
}
.button1:active, .a:active {
position: relative;
top: 1px;
}
.table {
font-family: verdana, Helvetica, sans-serif;
font-size: 12px;
color: #333;
background-color: #E4E4E4;
}
.table td {
background-color: #F8F8F8;
}
Captcha.php
<?php
session_start();
include("./phptextClass.php");
/*create class object*/
$phptextObj = new phptextClass();
/*phptext function to genrate image with text*/
$phptextObj->phpcaptcha('#162453','#fff',120,40,10,25);
?>
Demo.php
<?php session_start();
if(isset($_POST['Submit'])){
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){
$msg="<span style='color:red'>The Validation code does not match!</span>";// Captcha verification is incorrect.
}else{// Captcha verification is Correct. Final Code Execute here!
$msg="<span style='color:green'>The Validation code has been matched.</span>";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Secure Professional Captcha.</title>
<link href="./css/style.css" rel="stylesheet">
<script type='text/javascript'>
function refreshCaptcha(){
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</head>
<body>
<div id="frame0">
<h1>PHP Secure Professional Captcha Demo.</h1>
<p>More tutorials <a href="http://www.w3schools.in/">www.w3schools.in</a></p>
</div>
<br>
<form action="" method="post" name="form1" id="form1" >
<table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="table">
<?php if(isset($msg)){?>
<tr>
<td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
</tr>
<?php } ?>
<tr>
<tdalign="right" valign="top"> Validation code:</td>
<td><imgsrc="captcha.php?rand=<?php echo rand();?>" id='captchaimg'><br>
<label for='message'>Enter the code above here :</label>
<br>
<input id="captcha_code" name="captcha_code" type="text">
<br>
Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.</td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" type="submit" onclick="return validate();" value="Submit" class="button1"></td>
</tr>
</table>
</form>
</body>
</html>
Phptextclass.php
<?php
/*phptext class, version 1.0
created by www.w3schools.in (Gautam kumar)
April 26, 2014
*/
class phptextClass
{
public function phptext($text,$textColor,$backgroundColor='',$fontSize,$imgWidth,$imgHeight,$dir,$fileName)
{
/* settings */
$font = './calibri.ttf';/*define font*/
$textColor=$this->hexToRGB($textColor);
$im = imagecreatetruecolor($imgWidth, $imgHeight);
$textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);
if($backgroundColor==''){/*select random color*/
$colorCode=array('#56aad8', '#61c4a8', '#d3ab92');
$backgroundColor = $this->hexToRGB($colorCode[rand(0, count($colorCode)-1)]);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
}else{/*select background color as provided*/
$backgroundColor = $this->hexToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
}
imagefill($im,0,0,$backgroundColor);
list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize);
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
if(imagejpeg($im,$dir.$fileName,90)){/*save image as JPG*/
return json_encode(array('status'=>TRUE,'image'=>$dir.$fileName));
imagedestroy($im);
}
}
public function phpcaptcha($textColor,$backgroundColor,$imgWidth,$imgHeight,$noiceLines=0,$noiceDots=0,$noiceColor='#162453')
{
/* Settings */
$text=$this->random();
$font = './font/monofont.ttf';/* font */
$textColor=$this->hexToRGB($textColor);
$fontSize = $imgHeight * 0.75;
$im = imagecreatetruecolor($imgWidth, $imgHeight);
$textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);
$backgroundColor = $this->hexToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
/* generating lines randomly in background of image */
if($noiceLines>0){
$noiceColor=$this->hexToRGB($noiceColor);
$noiceColor = imagecolorallocate($im, $noiceColor['r'],$noiceColor['g'],$noiceColor['b']);
for( $i=0; $i<$noiceLines; $i++ ) {
imageline($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight),
mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), $noiceColor);
}}
if($noiceDots>0){/* generating the dots randomly in background */
for( $i=0; $i<$noiceDots; $i++ ) {
imagefilledellipse($im, mt_rand(0,$imgWidth),
mt_rand(0,$imgHeight), 3, 3, $textColor);
}}
imagefill($im,0,0,$backgroundColor);
list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize);
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
imagejpeg($im,NULL,90);/* Showing image */
header('Content-Type: image/jpeg');/* defining the image type to be shown in browser widow */
imagedestroy($im);/* Destroying image instance */
if(isset($_SESSION)){
$_SESSION['captcha_code'] = $text;/* set random text in session for captcha validation*/
}
}
/*for random string*/
protected function random($characters=6,$letters = '23456789bcdfghjkmnpqrstvwxyz'){
$str='';
for ($i=0; $i<$characters; $i++) {
$str .= substr($letters, mt_rand(0, strlen($letters)-1), 1);
}
return $str;
}
/*function to convert hex value to rgb array*/
protected function hexToRGB($colour)
{
if ( $colour[0] == '#' ) {
$colour = substr( $colour, 1 );
}
if ( strlen( $colour ) == 6 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
} elseif ( strlen( $colour ) == 3 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
} else {
return false;
}
$r = hexdec( $r );
$g = hexdec( $g );
$b = hexdec( $b );
return array( 'r' => $r, 'g' => $g, 'b' => $b );
}
/*function to get center position on image*/
protected function ImageTTFCenter($image, $text, $font, $size, $angle = 8)
{
$xi = imagesx($image);
$yi = imagesy($image);
$box = imagettfbbox($size, $angle, $font, $text);
$xr = abs(max($box[2], $box[4]));
$yr = abs(max($box[5], $box[7]));
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
return array($x, $y);
}
}
?>
Click on the below link to download the source code