What are the best practices for generating and displaying CAPTCHA images in PHP?
When generating and displaying CAPTCHA images in PHP, it is important to create images that are easily readable by humans but difficult for bots to decipher. One way to achieve this is by using random fonts, colors, and backgrounds for the CAPTCHA image. Additionally, adding noise and distortion to the image can further enhance its security.
<?php
session_start();
$width = 200;
$height = 50;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
$font = "path/to/font.ttf";
$text = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 6);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 10, 30, $textColor, $font, $text);
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
$_SESSION['captcha'] = $text;
?>
Keywords
Related Questions
- What best practices can be followed when converting PHP code to HTML for display purposes?
- How can one balance the desire for quick solutions with the importance of learning PHP for future tasks?
- How can one test the rendering of HTML and plain text emails in various email clients, both web-based and native?