PHP simple captcha script

A CAPTCHA is a type of challenge-response test used in website as an attempt to ensure that the response is generated by a human being. There are basically 3 types of captcha first one and widely used is image captcha , second is mathematical captcha and last one is vice captcha.

In this tutorial you will learn how to generate and use image captcha using php.

First generate captcha image

Here is php code to generate image with random code. Save it as captcha.php

<?php
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165); //background color blue
$fg = imagecolorallocate($im, 255, 255, 255);//text color white
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5,  $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

First start session to store captcha code in session then generate random code using php rand() function and write it on image generated by imagecreatetruecolor(). To change image background color edit line 6 and for text color edit line 7

Put captcha image in html form

<html>
<head>
<title>Test Form</title>
</head>
<body>
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>

Now validate Captcha response

<?php
session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
}
else
{
die("Wrong Code Entered");
}
?>

first start session to access $_SESSION[“code”] variable then compare it with posted captcha response. If both are same then run your code else exit from code with message Wrong Code Entered

Demo Download

Published by Sunny

A Mechanical engineer by education and web developer by passion and profession. He lives in Lucknow, India. Currently earning his livings by hitting keyboad. ;)

Join the Conversation

30 Comments

  1. Nice one! Thank you, sunny.

    Really basic, really simple, but good enough to keep 99,99% of all bots out of my AJAX chat.

  2. hi,
    i added all file and code in my plugin. but captcha image not showing. on my localhost site.

    after click on enter i t error The requested URL /mytheme/validate.php was not found on this server.

    Please help

  3. Perfect. Easy to implement the code .. Moreover it isn’t time consuming as captcha text is clearly visible and hence users can enter the captcha text without breaking their head.. thank you!

  4. its great thanks for all this help everything is explain so well that i never be feel diffculty to embed it in my code

  5. after validation, how can we send the user to one specific page (exemple, a page where the user could download a document ou fill a form) ??

  6. when i run it it get those error
    Fatal error: Call to undefined function imagecolorallocate() in C:\wamp\www\captcha\captcha.php on line 6

    please istruct me how to clear this error.

  7. Thanks – this captcha works great, just wondering though has anyone had an issue with opera browser? It seems to be the only one that has problems with it …. on my system anyway. All other browsers are fine – I assumed opera would be fine as it seems to use the same core as chrome?

    1. just refresh image using JavaScript
      Put it in section
      <script type="text/javascript">
      function reloadImg() {
      var d=new Date();
      document.getElementById("capimg").src="captcha.php?a="+d.getTime();
      }
      </script>

      replace <img src="captcha.php" />
      with
      <img src="captcha.php" id="capimg" /><a href="javascript:reloadImg()" rel="nofollow">Reload Image</a>

Leave a comment

Leave a Reply to Edwin Siro Cancel reply

Your email address will not be published. Required fields are marked *