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.
captcha.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 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);
?>
test.php
<?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>
Original text: link