php验证码

demo:https://www.dongshushu.com/yanzhengma/index.php

验证码authcode.php

<?php 

//设置画布大小和颜色
$image = imagecreatetruecolor(100,30);

$bgcolor = imagecolorallocate($image,255,255,255);

imagefill($image,0,0,$bgcolor);

//设置session变量
session_start();
$code = '';


// 输出验证码内容

for($i=0;$i<4;$i++){

$data = 'abcdefghijklmnopqrstuvwxyz123456789';

$content = substr($data,rand(0,strlen($data)-1),1);


$textcolor = imagecolorallocate($image,rand(0,100),rand(0,100),rand(0,100));

$fontsize = 6 ;

$x = ($i*100/4)+6;

$y = rand(2,10);

imagestring($image,$fontsize,$x,$y,$content,$textcolor);

$code.=$content;

}


$_SESSION['code']=$code;

//echo $_SESSION['code']; exit;
// 打印干扰像素点
for($i=0; $i<200; $i++){


$pixelcolor = imagecolorallocate($image,rand(100,255),rand(100,255),rand(100,255));

imagesetpixel($image, rand(1,99) , rand(1,29) , $pixelcolor);

}

// 打印干扰线
for($i=0; $i<3; $i++){

        $linecolor = imagecolorallocate($image,rand(100,255),rand(100,255),rand(100,255));
        imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);

}
header('content-type:image/png');

imagepng($image);

//end
imagedestroy($image);

表单页面 index.php

<?php 
session_start();

if(isset($_REQUEST['authcode'])){
	if(strtolower($_REQUEST['authcode']) == $_SESSION['code']){
		echo "验证成功";
	}else{
		echo "验证失败";
	}
	exit();
}

?>
<!DOCTYPE html>
<html lang="cn">
<head>
	<meta charset="UTF-8">
	<title>验证码</title>
</head>
<body>
	<h1>验证码</h1>
	<hr>
	<form action="" method="post">
		<img src="./authcode.php?random=<?php echo rand(); ?>" alt="验证码" id="authcode"><a href="javascript:;" onclick="changeUrl()">换一个</a><br>
		<label for="">验证码</label><input type="text" name="authcode" placeholder="请输入验证码"><br>
		<input type="submit" value="提交">
	</form>
	<script>
	function changeUrl(){
		document.getElementById('authcode').src='./authcode.php?random='+Math.random();
	}
	</script>
</body>
</html>

评论

发表回复