PHP highly customizable security verification code code

  • 2020-05-10 17:49:22
  • OfStack

 
<?php 
public function captcha(){ 
$font_dir = $_SERVER ["DOCUMENT_ROOT"] . "your_ttf_file.ttf"; //  Font library  
$img_w = 58; //  Set image width  
$img_h = 20; //  Set image height  
$font_size = 11; //  The font size  
$angle_l = -10; //  The left Angle  
$angle_r = 10; //  The right Angle  
$code_str = "ABCDEFGHJKLMNPQRSTUVWXYZ36"; 
$word_len = 4; //  Verification code number  
$padding = 5; //  Space between each word  
$margin = 2; //  The left margin  
$base_line = 15; //  Text base position  
$base_line_offset = 2; //  Baseline offset  
$pixel_num = 3; //  Number of impurities  
$pixel_color= 8; //  Miscellaneous points only  $pixel_color  Kinds of color   The total number of miscellaneous points is zero $pixel_num*$pixel_color 
$noise_font_size = 1; //  Dot font size  
$session_key= "my.xoyo_captcha"; // The custom session Key name  

header("Cache-Control: no-cache, must-revalidate"); 
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
header("Pragma: no-cache"); 
header("Cache-control: private"); 
header('Content-Type: image/png'); 

session_start(); 
$word = ""; 
$code_str_len = strlen($code_str) - 1; 
for ($i = 0; $i < $word_len; $i++) { 
$word.= $code_str[rand(0, $code_str_len)]; 
} 
$_SESSION [$session_key] = strtolower($word); 
$image = imagecreatetruecolor($img_w, $img_h); 
imagefilledrectangle($image, 0, 0, $img_w - 1, $img_h - 1, imagecolorallocate($image, mt_rand(235, 255), mt_rand(235, 255), mt_rand(235, 255))); 

// To draw all  
for($i = 0; $i < $pixel_color; $i++){ 
$noise_color = imagecolorallocate( $image, mt_rand(150,225), mt_rand(150,225), mt_rand(150,225) ); 
for($j = 0; $j < $pixel_num; $j++) { 
imagestring( $image, $noise_font_size, mt_rand(-10, $img_w), mt_rand(-10, $img_h), $code_str[mt_rand(0, $code_str_len)], $noise_color ); 
} 
} 

// Rendering text  
for ($i = 0; $i < $word_len; ++$i) { 
$color = imagecolorallocate($image, mt_rand(0, 100), mt_rand(20, 120), mt_rand(50, 150)); 
imagettftext($image, $font_size, mt_rand($angle_l, $angle_r), $margin, mt_rand($base_line-$base_line_offset, $base_line+$base_line_offset), $color, $font, mb_substr($word, $i, 1, 'utf-8')); 
$margin += (imagefontwidth($font_size) + $padding); 
} 

imagepng($image); 
imagedestroy($image); 
exit; 
} 

Related articles: