php的加法_PHP实现加法、减法验证码

本文介绍了如何使用PHP创建加法和减法的验证码,通过随机生成两个数字进行运算,将结果存储到session中,同时在图像上显示算式。文章探讨了避免除不尽情况的方法,建议用乘法替代除法,确保结果不出现负数。此外,还提供了相关推荐资源。

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

本篇文章给大家分享的是PHP实现加法、减法验证码,有兴趣的朋友可以看一看

header('Content-Type: image/png');

$im = imagecreatetruecolor( 200 , 50 );

// Create some colors

$white = imagecolorallocate($im, 255, 255, 255);

$grey = imagecolorallocate($im, 128, 128, 128);

$black = imagecolorallocate($im, 0, 0, 0);

imagefilledrectangle($im, 0, 0, 200, 49, $white);

// The text to draw

$rand = rand( 1 ,2 ) ;

$one = rand(1,9);

$two = rand(1,9);

if( $rand == 1 ){

$result = $one + $two;

$text = "$one+$two=?";

}else{

if( $one < $two ){

list( $two , $one ) = [ $one , $two ];

}

$result = $one - $two;

$text = "$one-$two=?";

}

session_start();

$_SESSION['vcode'] = $result;

// Replace path by your own font path

$font = './Arvo-Regular.ttf';

//imageline( $im , 0 , rand( 1,49 ) , 199 , 30 , $grey );

// Add the text

$i = 0;

$len = strlen( $text );

while( $i < $len ){

if( is_numeric( $text[$i] ) ){

imagettftext($im, 20, rand(-45,45), 20 * ($i+1) , 30, $black, $font, $text[$i]);

}else{

imagettftext($im, 20, 0 , 20 * ($i+1) , 30, $black, $font, $text[$i]);

}

//echo $text[$i];

$i ++;

}

// Using imagepng() results in clearer text compared with imagejpeg()

imagepng($im);

imagedestroy($im);

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

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

2*3=6

6/2=3

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

相关推荐:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值