PHP implements an instance of color changing captcha

  • 2020-12-07 03:59:11
  • OfStack

 
<?php 
header("Content-type: image/png,charset='utf-8'"); 
$im = imagecreatetruecolor(400, 30); 
// white  
$white = imagecolorallocate($im, 255, 255, 255); 
// red  
$red = imagecolorallocate($im, 255, 0, 0); 
// black  
$black=imagecolorallocate($im, 0, 0, 0); 
// green  
$green=imagecolorallocate($im, 0, 255, 0); 
// blue  
$blue=imagecolorallocate($im, 0, 0, 255); 
$color_arr=array($green,$blue,$red); 
$color=array_rand($color_arr); 
$text = ' This captcha is a freak of mine '; 
$textlen=iconv_strlen($text,'utf-8');// Calculate the length of the string  
// Randomly intercept two characters and display with color change  
$p1=rand(1,$textlen)-1; 
while(($p2=rand(1,$textlen)-1)==$p1); 
$w1=iconv_substr($text,$p1,1,'utf-8'); 
$w2=iconv_substr($text,$p1,1,'utf-8'); 
// The font file   ( PS : T good php Q Buckle � : 276167802 To validate: csl )  
$font = 'simkai.ttf'; 
imagefilledrectangle($im, 0, 0, 399, 29, $white); 
for($i=0;$i<$textlen;$i++) 
{ 
if($i==$p1||$i==$p2) 
{ 
imagettftext($im, 15, 0, 20*($i-1)+20, 20, $color_arr[$color], $font, iconv_substr($text,$i,1,'utf-8')); 
} 
else 
{ 
imagettftext($im, 15, 0, 20*($i-1)+20, 20, $black, $font, iconv_substr($text,$i,1,'utf-8')); 
} 
} 
imagepng($im); 
imagedestroy($im); 
?> 

The characters in the captcha are not of the same color. It is safer to let the user enter a captcha of the specified color.

Related articles: