PHP实现加法、减法验证码

这篇博客介绍了如何使用PHP创建包含加法或减法的验证码。通过随机生成两个数字,然后计算结果并将其存储在session中,验证码图片显示算式供用户验证。文章还提及了除法和乘法验证码的实现思路,例如通过乘法避免除不尽的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

 2*3=6 

6/2=3 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值