Generate Captcha Image with PHP [Updated]

By: Sunil Kumar |  In: PHP  |  Last Updated: 2017/11/08

The reason to write this tutorial is to demonstrate how to create captcha image in your application using PHP. By now, we?ve all encountered captcha images in online forms. Captchas are a necessary evil, and this article will teach you how they are made.

CAPTCHA is a simple test to determine if a user is a computer or a human. It is used to prevent spam abuse on the websites. So if you use CAPTCHA on your website forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms.

1. Generating Captcha Image

You must have the GD(Graphics Draw) library installed before proceeding. This library enables drawing of graphics and images through built-in PHP functions.
Generally, it is installed with the PHP package.

First thing you need to create a captcha image.Your captcha image must be a random string without any common pattern so that no program can predict the text inside the captcha image.


    <!-- captcha.php -->

<?php
session_start();
?>

    <title>Generate captcha image</title>
    <body style="background-color:#ccc;">

<?php
    create_image();
    display();
    function display()
    {
?>
       <div style="text-align:center;">
            <h3>TYPE THE TEXT YOU SEE IN THE IMAGE</h3>
            <div style="display:block;margin-bottom:20px;margin-top:20px;">
                <img src="captcha_image.png">
            </div>
            <form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
                <input type="submit" value="refresh captcha">
            </form>
            <form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST"/ >
                <input type="text" name="input"/>
                <input type="hidden" name="flag" value="1"/>
                <input type="submit" value="submit" name="submit"/>
            </form>
            
        </div>      


<?php
    }

    function  create_image()
    {
        $image = imagecreatetruecolor(200, 50);       
        $background_color = imagecolorallocate($image, 255, 255, 255);  
        imagefilledrectangle($image,0,0,200,50,$background_color); 

        $line_color = imagecolorallocate($image, 64,64,64);
        $number_of_lines=rand(3,7);

        for($i=0;$i<$number_of_lines;$i++)
        {
            imageline($image,0,rand()%50,250,rand()%50,$line_color);
        }

        $pixel = imagecolorallocate($image, 0,0,255);
        for($i=0;$i<500;$i++)
        {
            imagesetpixel($image,rand()%200,rand()%50,$pixel);
        }  

        $allowed_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $length = strlen($allowed_letters);
        $letter = $allowed_letters[rand(0, $length-1)];
        $word='';
        $text_color = imagecolorallocate($image, 0,0,0);
        $cap_length=6;// No. of character in image
        for ($i = 0; $i< $cap_length;$i++)
        {
            $letter = $allowed_letters[rand(0, $length-1)];
            imagestring($image, 5,  5+($i*30), 20, $letter, $text_color);
            $word.=$letter;
        }

        $_SESSION['captcha_string'] = $word;

        imagepng($image, "captcha_image.png");
    }
?>
    </body>

  

2. Validating Captcha Image

It is here that the user?s response is taken and after processing it, he/she receives a reply. when you submit the form get the value of TextBox and compare it with the Session value.


    if($_SESSION['captcha_string']==$_POST["input"])
    {
        echo "Thank you. You can proceed";
    }
    else
    {
        echo "Sorry. Try again";
    }
    unset($_SESSION['captcha_string']);
  

Conclusion

Making various types of captchas in PHP is very easy. Now you can easily generate a captcha image to stop spamming on the website.

Comments


Leave a Comment

Your email address will not be published.

*


Sunil Kumar


I am the owner of acmeextension. I am a passionate writter and reader. I like writting technical stuff and simplifying complex stuff.
Know More

Subscribe to our mailing list


%d bloggers like this: