*.html
<input type="text" name="captcha" id="captcha" placeholder="验证码" maxlength="">
<img src="captcha.php" onclick="this.src='captcha.php?' + Math.random();" width="" height="">
api.php
<?php
session_start(); $dataObj = json_decode($HTTP_RAW_POST_DATA);
if(strtolower($_SESSION["code"]) != strtolower($dataObj->captcha)){
$msg = '不正确';
}else{
//正确
}
captcha.php
<?php
session_start();
header ('Content-Type: image/png'); $image=imagecreatetruecolor(, );
//背景颜色为白色
$color=imagecolorallocate($image, , , );
imagefill($image, , , $color); $code='';
for($i=;$i<;$i++){
$fontSize=;
$x=rand(,)+$i*/;
$y=rand(, );
// $data='abcdefghijklmnpqrstuvwxyz123456789';
$data='ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
$string=substr($data,rand(, strlen($data)),);
$code.=$string;
$color=imagecolorallocate($image,rand(,), rand(,), rand(,));
imagestring($image, $fontSize, $x, $y, $string, $color);
}
$_SESSION['code']=$code;//存储在session里 for($i=;$i<;$i++){
$pointColor=imagecolorallocate($image, rand(, ), rand(, ), rand(, ));
imagesetpixel($image, rand(, ), rand(, ), $pointColor);
}
for($i=;$i<;$i++){
$linePoint=imagecolorallocate($image, rand(, ), rand(, ), rand(, ));
imageline($image, rand(, ), rand(, ), rand(,), rand(, ), $linePoint);
}
imagepng($image);
imagedestroy($image);