How to Generate Captcha Image in PHP ? - GeeksforGeeks

05 Oct, 2021
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 steal 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 
PHP
<?php  // We start a session to access// the captcha externally!session_start();  // Generate a random number// from 1000-9999$captcha = rand(1000, 9999);  // The captcha 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 backgroundimagefill($im, 0, 0, $bg);  // Print the captcha text in the image// with random position & sizeimagestring($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 imageheader('Content-type: image/png');  // Finally output the captcha as// PNG image the browserimagepng($im); // Free memoryimagedestroy($im);?>
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: 
HTML
<?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>
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. 
youngneer
gulshankumarar231
PHP-Misc
PHP
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?