php生成token并验证码_随机验证码的使用(PHP:生成图像 + 服务器端存储 )

这篇博客详细介绍了如何使用HTML和PHP实现一个注册表单,包括用户名、密码和验证码的输入。PHP代码展示了如何生成随机的四字符验证码图片,并在用户提交时验证其有效性。同时,代码还涉及到了会话管理,确保验证码的一次性使用。
摘要由CSDN通过智能技术生成

html代码:

img, input {

vertical-align: middle;

}

.vcode {

cursor: pointer;

}

注册新用户

用户名:

密码名:

验证码:

vcode.php

var vcode = document.querySelector('.vcode');

vcode.onclick = function(){

//若URL没有改变,浏览器不会重发请求

//this.src = 'vcode.php';

//必须保证URL值改变,浏览器才会发请求

this.src = 'vcode.php?_='+Math.random();

}

register.php

/***

*接收客户端提交的注册信息,验证提交的随机验证码是否有效

*若有效,则保存入数据库

*/

header("Content-Type: application/json");

@$n = $_REQUEST['uname'] or die('{"code":-2, "msg":"uname required"}');

@$p = $_REQUEST['upwd'] or die('{"code":-3, "msg":"upwd required"}');

@$v = $_REQUEST['vcode'] or die('{"code":-4, "msg":"vcode required"}');

session_start();

$vs = $_SESSION['vcode_in_server'];

//判断客户端提交的验证码与服务器端保存验证码是否一致

if(strtoupper($v)!==strtoupper($vs)){

die('{"code":-9,"msg":"vcode invalid"}');

}

//所有的验证通过了,开始执行数据库INSERT

//INSERT INTO user VALUES(NULL, '$n', '$p');

$output = [

'request'=>$_REQUEST,

'session'=>$_SESSION

];

echo json_encode($output);

随机生成验证码图片的vcode.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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值