GENWiki

Premier IT Outsourcing and Support Services within the UK

User Tools

Site Tools


php:generating_captcha_images_with_php

PHP Dynamic Captcha Images

We can use PHP's built in image handling features to generate a small image into which we insert a 4 digit captcha. We'll return a string which can then be used in a html img tag as a source.

function captchaimage($captcha) {
	
	// We return an image string that can be used as a <img src="" content
	//
	$im = imagecreatetruecolor(50, 24); 
	$bg = imagecolorallocate($im, 22, 86, 165);
	$fg = imagecolorallocate($im, 255, 255, 255);
	imagefill($im, 0, 0, $bg);
	imagestring($im, rand(1, 7), rand(1, 7),rand(1, 7),  $captcha, $fg);

	$temp = fopen('php://memory', 'rw');  // can use php://temp or php://memory
	imagepng($im,$temp);
	rewind($temp);
	$image=fread($temp,16384); //read it back in again
	fclose($temp); // close the file
	$imagestring="data:image/png;base64,".base64_encode($image);
	imagedestroy($im);
	
	return $imagestring;
}

To call this, we first of all generate a random 4 digit number:

$captcha = rand(1000, 9999);

Now we call the code and get the img src string:

$cimg=captchaimage($captcha);

Then within the html we can simply show the image with:

<img src="<?php echo $cimg; ?>">

You should save the 4 digit number in a session variable, e.g. $_SESSION["CAPTCHA"]=$captcha; and then compare the number from the form with this.

/home/gen.uk/domains/wiki.gen.uk/public_html/data/pages/php/generating_captcha_images_with_php.txt · Last modified: 2023/01/31 11:41 by genadmin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki