PHP实现加法、减法验证码

[php]  view plain  copy
  1.   
  2. header('Content-Type: image/png');  
  3. $im = imagecreatetruecolor( 200 , 50 );  
  4.   
  5. // Create some colors  
  6. $white = imagecolorallocate($im, 255, 255, 255);  
  7. $grey = imagecolorallocate($im, 128, 128, 128);  
  8. $black = imagecolorallocate($im, 0, 0, 0);  
  9.   
  10. imagefilledrectangle($im, 0, 0, 200, 49, $white);  
  11.   
  12. // The text to draw  
  13. $rand = rand( 1 ,2 ) ;  
  14. $one = rand(1,9);  
  15. $two = rand(1,9);  
  16. if$rand == 1 ){  
  17.   
  18.     $result = $one + $two;  
  19.     $text = "$one+$two=?";  
  20.   
  21. }else{  
  22.     if$one < $two ){  
  23.         list( $two , $one ) = [ $one , $two ];  
  24.     }  
  25.     $result = $one - $two;  
  26.     $text = "$one-$two=?";  
  27. }  
  28.   
  29. session_start();  
  30. $_SESSION['vcode'] = $result;  
  31. // Replace path by your own font path  
  32. $font = './Arvo-Regular.ttf';  
  33.   
  34. //imageline( $im , 0 , rand( 1,49 ) , 199 , 30 , $grey );  
  35.   
  36. // Add the text  
  37. $i = 0;  
  38. $len = strlen$text );  
  39. while$i < $len  ){  
  40.     ifis_numeric$text[$i] ) ){  
  41.         imagettftext($im, 20, rand(-45,45), 20 * ($i+1) , 30, $black$font$text[$i]);  
  42.     }else{  
  43.         imagettftext($im, 20, 0 , 20 * ($i+1) , 30, $black$font$text[$i]);  
  44.     }  
  45. //echo $text[$i];  
  46.     $i ++;  
  47. }  
  48. // Using imagepng() results in clearer text compared with imagejpeg()  
  49. imagepng($im);  
  50. imagedestroy($im);  

加法减法可以这么实现,除法和乘法也类似 

除法时候会遇到除不尽的情况,可以换一种思路,使用乘法解决 

 2*3=6 

6/2=3 

这样就不会出现负数的情况了

你可能感兴趣的:(PHP)