How to Generate Captcha Image in 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.

For this article we won’t use any advanced GD functions. But if you want to learn more about GD then you read the various GeeksforGeeks articles about it.



So the main idea of creating an image-captcha is to first have a captcha.php which would start a session and generate captchas.

  • captcha.php
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
       
    // We start a session to access
    // the captcha externally!
    session_start();
       
    // Generate a random number
    // from 1000-9999
    $captcha = rand(1000, 9999);
       
    // The capcha will be stored
    // for the session
    $_SESSION["captcha"] = $captcha;  
       
    // Generate a 50x24 standard captcha image
    $im = imagecreatetruecolor(50, 24);  
      
    // Blue color
    $bg = imagecolorallocate($im, 22, 86, 165);
      
    // White color
    $fg = imagecolorallocate($im, 255, 255, 255);
       
    // Give the image a blue background
    imagefill($im, 0, 0, $bg); 
       
    // Print the captcha text in the image
    // with random position & size
    imagestring($im, rand(1, 7), rand(1, 7),
                rand(1, 7),  $captcha, $fg);
       
    // VERY IMPORTANT: Prevent any Browser Cache!!
    header("Cache-Control: no-store,
                no-cache, must-revalidate"); 
       
    // The PHP-file will be rendered as image
    header('Content-type: image/png');
       
    // Finally output the captcha as
    // PNG image the browser
    imagepng($im); 
      
    // Free memory
    imagedestroy($im);
    ?>

    chevron_right

    
    

When you can run captcha.php, you should have a small image with a captcha printed on it. Now only thing we need to do is create a test.php which uses captcha.php and validates captcha based on user’s input. For this example, we’ll keep it simple. When the user gives us a wrong captcha we print an error message and when he gives us a correct captcha we might want to redirect the user to a different URL but for now, we’ll simply print a message.

  • test.php:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    session_start();
    $msg = '';
      
    // If user has given a captcha!
    if (isset($_POST['input']) && sizeof($_POST['input']) > 0)
      
        // If the captcha is valid
        if ($_POST['input'] == $_SESSION['captcha'])
            $msg = '<span style="color:green">SUCCESSFUL!!!</span>';
        else
            $msg = '<span style="color:red">CAPTCHA FAILED!!!</span>';
    ?>
       
    <style>
        body{
            display:flex;
            flex-direction:column;
            align-items: center;
            justify-content: center;
        }
    </style>
       
    <body>
        <h2>PROVE THAT YOU ARE NOT A ROBOT!!</h2>
          
        <strong>
            Type the text in the image to prove
            you are not a robot
        </strong>
       
        <div style='margin:15px'>
            <img src="captcha.php">
        </div>
          
        <form method="POST" action=
                " <?php echo $_SERVER['PHP_SELF']; ?>">
            <input type="text" name="input"/>
            <input type="hidden" name="flag" value="1"/>
            <input type="submit" value="Submit" name="submit"/>
        </form>
          
        <div style='margin-bottom:5px'>
            <?php echo $msg; ?>
        </div>
          
        <div>
            Can't read the image? Click
            <a href='<?php echo $_SERVER['PHP_SELF']; ?>'>
                here
            </a>
            to refresh!
        </div>
    </body>

    chevron_right

    
    

  • Output:

Even though Captchas may be very annoying yet without Captchas we might not know the Internet as we do know. Captchas are essential for fighting spam and keeping the web alive.

Do not use this script in production code: The main issue with our image captcha is that any experienced programmer can easily create a bot that can process the images and extract the text and send a POST request and verify itself as a human. To tackle this issue we can perhaps add random lines, dots (unit-length circles), etc in the foreground but image processing has developed to the extent that it would only make it a little difficult for the programmer to process the image and stringify it.

So the best solution is to use a specialized and well-tested library like Google’s reCAPTCHA which is both easy to integrate in your PHP environment and also somewhat less “pain in the neck” compared to those traditional “type the text” since it can sometimes not generate a captcha at all if it already knows the user is not a bot based on his previous activities.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : youngneer