What are the best practices for creating and displaying captchas in PHP?
To create and display captchas in PHP, it is important to use a combination of random characters, distortion techniques, and validation checks to ensure security. Captchas help prevent automated bots from submitting forms and protect against spam attacks on websites.
<?php
session_start();
$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 6);
$_SESSION['captcha'] = $randomString;
$im = imagecreatetruecolor(100, 30);
$bgColor = imagecolorallocate($im, 255, 255, 255);
$textColor = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 100, 30, $bgColor);
imagettftext($im, 15, 0, 10, 20, $textColor, 'arial.ttf', $randomString);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Keywords
Related Questions
- How can PHP developers ensure the integrity and security of their database operations when interacting with user input?
- What is the purpose of using Ajax in PHP and what are the common challenges faced when implementing asynchronous data loading?
- How can output buffering and data flushing be optimized in PHP scripts to ensure timely and accurate data transmission between scripts and external processes like shell scripts?