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


Liked It? Get Free updates in your Email

Delivered by feedburner

30 thoughts on “PHP simple captcha script

  1. Sam
    #

    Excellent !!
    Users struggle to fill up form due to alphanumeric case sensitive captchas.
    This one is cool ..

    Reply
  2. spacko
    #

    Nice one! Thank you, sunny.

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

    Reply
  3. Brian Cherdak
    #

    should the captcha session be destroyed after the form has been filled and successfully registered?

    Reply
  4. Dave Luke
    #

    Excellent! Simple! Clean!

    Thank You!

    Reply
  5. Dave
    #

    Yea…short; working…cool;

    Reply
  6. Ajantha
    #

    Thanx a lot……….. this is working nicely…..!!

    Reply
  7. H. Guti
    #

    Thank you, simple and easy to implement.

    Reply
  8. mukta
    #

    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

    Reply
  9. Agusta Bank
    #

    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!

    Reply
  10. Pingback: 10 PHP tips for web developer | Web Tools

  11. Øystein Buvik
    #

    Finally a captcha that is easy and works great =)

    Thank you!

    Reply
  12. Dab
    #

    Ex. You entered 8718cc? The system will accept it even though it is wrong

    Reply
  13. Waseem Ahmad
    #

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

    Reply
  14. sd
    #

    captcha image not show

    Reply
  15. Ajithkumar
    #

    Thank you

    Reply
  16. Colin
    #

    Thank you, works great!

    Reply
  17. cyllantro
    #

    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) ??

    Reply
  18. adolfu kavenuke
    #

    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.

    Reply
    1. sunny Post author
      #

      enable php_gd2 extension in your wamp

      Reply
  19. Sam
    #

    Excellent, Without knowing php i was able to do. Great Work!

    Reply
  20. Bhagwat Pawar
    #

    very good. working fine. thank you.

    Reply
  21. Mike
    #

    Nice! Is it possible to give the captcha a transparent background instead of colored? If so what is the code..
    thanks!

    Reply
  22. Mike
    #

    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?

    Reply
  23. archana
    #

    i have done all same but still not working … plz help

    Reply
  24. Umesh Gaire
    #

    how it is possible to reload captcha if it is needed

    Reply
    1. sunny Post author
      #

      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>

      Reply

Leave a Reply

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