Skip to content
PHP Logo

How can PHP be used to generate dynamic graphics for authentication purposes?

To generate dynamic graphics for authentication purposes in PHP, you can use the GD library to create CAPTCHA images. CAPTCHA images are commonly used to verify that a user is a human and not a bot. By generating a random image with distorted text that the user must input correctly, you can add an extra layer of security to your authentication process.

php
<?php
session_start();

$width = 200;
$height = 50;

$image = imagecreatetruecolor($width, $height);

$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);

$code = substr(md5(mt_rand()), 0, 6);

$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 10, 30, $textColor, 'arial.ttf', $code);

$_SESSION['captcha_code'] = $code;

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>