从服务器中获取验证码

为啥要有验证码,因为防止机器的攻击,如果没有验证码,机器会不断的申请账号,这样服务器如果不够抢到很容易被垮掉,

通过验证码人很容易识别但是机器是比较难,即使机器识别了但是也需要很久时间。这样大大降低了服务器的安全。

下面代码

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
img, input {
vertical-align: middle;
}
.vcode {
cursor: pointer;
}
</style>
</head>
<body>
<h3>注册新用户</h3>

<form action="3_register.php">
用户名:<input name="uname"><br/>
密码名:<input name="upwd"><br/>
验证码:<input name="vcode">
<img class="vcode" src="vcode.php"><br>

<input type="submit">
</form>
<script>
var vcode = document.querySelector('.vcode');
vcode.onclick = function(){
//若URL没有改变,浏览器不会重发请求
//this.src = 'vcode.php';
//必须保证URL值改变,浏览器才会发请求
this.src = 'vcode.php?_='+Math.random();
}

</script>
</body>
</html>

 

 

 

 

 

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

//在服务器端内存中生成一张随机验证码图片
$w = 80;
$h = 20;
$img = imagecreatetruecolor($w, $h);

//为图片生成随机的背景颜色——绘制矩形
$c = imagecolorallocate($img,rand(180,240),rand(180,240),rand(180,240));
imagefilledrectangle($img,0,0,$w, $h, $c);

//绘制四个随机的字符
$pool = 'ABCEFGHJKLMNPQRSTWXY23456789';
$vcode = '';
for($i=0; $i<4; $i++){
$s = $pool[rand(0, strlen($pool)-1)]; //随机字符
$vcode .= $s; //保存所有的字符
$fs = rand(12, 24); //随机的字体大小
$an = rand(-45,45); //随机旋转角度
$x = $i*20+5; //每个字符的X坐标
$y = rand(12, 22); //每个字符的Y坐标
$c = imagecolorallocate($img,rand(80,180),rand(80,180),rand(80,180));
$font = 'simhei.ttf';
imagettftext($img,$fs,$an,$x,$y,$c,$font,$s);
}
//为了在下一个页面:register.php页面使用该验证,判断用户输入是否正确
//必须把此处生成的随机验证码保存在当前客户端所对应的session空间中
session_start();
$_SESSION['vcode_in_server'] = $vcode;

 

//绘制5条随机干扰线
for($i=0; $i<5; $i++){
$c = imagecolorallocate($img,rand(20,240),rand(20,240),rand(20,240));
imageline($img, rand(0,$w),rand(0,$h),rand(0,$w),rand(0,$h),$c);
}

//绘制50个杂色点——半径为1的圆
for($i=0; $i<50; $i++){
$c = imagecolorallocate($img,rand(20,240),rand(20,240),rand(20,240));
imagearc($img,rand(0,$w),rand(0,$h),1,1,0,360,$c);
}


//把服务器内存中的图片输出给客户端
imagepng($img);
//从服务器内存中删除图片
imagedestroy($img);

转载于:https://www.cnblogs.com/hduhdc/p/6270855.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值