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 are common pitfalls when creating directories in PHP and setting access permissions?
- How can developers debug issues related to browser behavior and external URL execution when using a PHP proxy for Facebook content?
- What are some potential pitfalls of relying on the FILE array for image type information in PHP?