Simple PHP CAPTCHA

Simple PHP CAPTCHA

Here is a little snippet for anyone who needs it.

What it does?   Generates a random character string, stores it to a session variable (for verification), then renders a png image with a white background and random colors of the random characters.

Change any variables you need.  And call is using a simple <img> tag.

Here’s the code:

<?

$string = '';
// String of characters to randomly render
$chars = 'a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,G,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,$,%,&,*,@,#,~';
$ca = explode(',', $chars);
// Shuffle up the array
shuffle($ca);
// Now make it a complete string, but only allow 8 characters
foreach (array_slice($ca, 0, 8) as $ltr) {
	$string .= $ltr;
}
//Store the string in the session
$_SESSION['SecImg'] = $string;
//Set the browser header to render this as an image
header("Content-type: image/png");
//Make the initial image, specifying the dimensions 85px wide, 20px tall
$image  = imagecreate(85, 20);
//Set a white background
imagecolorallocate($image, 255, 255, 255);	
//Loop through our string, and create a sub-image to through on to our main image
for ($i = 0; $i <= strlen($string); $i++) {
	//Randomize the letter color   
	$textcolor = imagecolorallocate($image, rand(0, 150), rand(0, 150), rand(0, 150));
	//Add the letter to the image, randomize the size of the font, and move the letter to the next available space
	imagestring($image, rand(2, 5), (10*$i), 1, $string[$i], $textcolor);     	
}
//SHOW IT
imagepng($image);
//Clean Up
imagedestroy($image);
unset($ca, $string);

?>

 

Kevin Pirnie
22 Years of PC and server maintenance & over 17 years of web development/design experience; you can rest assured that I take every measure possible to ensure your computers are running to their peak potentials. I treat them as if they were mine, and I am quite a stickler about keeping my machines up to date and optimized to run as well as they can.