使用php怎么实现一个网站验证码功能

发布时间:2021-01-30 14:39:15 作者:Leah
来源:亿速云 阅读:134

今天就跟大家聊聊有关使用php怎么实现一个网站验证码功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

核心:img.php

这个页面生成一张验证码并将正确数值写入 Session

随机一个4位验证码

$check=rand(1000,9999); 

将生成的验证码写入session

Session_start(); 
$_SESSION["check"] = $check;

创建一张图片

$im = imagecreate(80,30);

由于这种图片的背景默认是黑色的所以我们要用白色填充。

imagefill($im,0,0,ImageColorAllocate($im, 255,255,255)); 

使用imageline随机绘制两条实线

$y1=rand(0,30); 
$y2=rand(0,30); 
$y3=rand(0,30); 
$y4=rand(0,30); 
imageline($im,0,$y1,70, $y3,000); 
imageline($im,0,$y2,70, $y4,000);

在随机位置绘制文字

$strx=rand(3,15); 
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,0,1),ImageColorAllocate($img,34,87,100)); 
$strx+=rand(15,20);
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,1,1),ImageColorAllocate($img,781,117,78)); 
$strx+=rand(15,20);
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,2,1),ImageColorAllocate($img,160,40,40)); 
$strx+=rand(15,20);
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,3,1),ImageColorAllocate($img,25,55,10));

输出图像

Header("Content-type: image/PNG"); 
ImagePNG($img);

结束,下面是完整代码

<?php $check=rand(1000,9999);
Session_start(); 
$_SESSION["check"] = $check; 
$img = imagecreate(80,30); 
imagefill($img,0,0,ImageColorAllocate($img,255,255,255)); 
$y1=rand(0,30); 
$y2=rand(0,30); 
$y3=rand(0,30); 
$y4=rand(0,30); 
imageline($img,0,$y1,70, $y3,ImageColorAllocate($img,55,255,25)); 
imageline($img,0,$y2,70, $y4,ImageColorAllocate($img,55,55,255)); 
$strx=rand(3,15); 
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,0,1),ImageColorAllocate($img,34,87,100)); 
$strx+=rand(15,20);
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,1,1),ImageColorAllocate($img,781,117,78)); 
$strx+=rand(15,20);
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,2,1),ImageColorAllocate($img,160,40,40)); 
$strx+=rand(15,20);
$stry=rand(2,15); 
imagestring($img,5,$strx,$stry,substr($check,3,1),ImageColorAllocate($img,25,55,10)); 
Header("Content-type: image/PNG"); 
ImagePNG($img);

用户界面:index.php

想必大家都知道怎么做,我就直接给出代码了

 <!DOCTYPE html>
<html>
<body>
<form action="action.php" method="post">
<input type="text" name="cikle" placeholder="验证码">
<br>
<img id="cikle"  src="img.php"><input type="submit" value="Submit">
</form> 
</body>
</html>

以上的代码将用户输入的数值传递到“action.php”中

检查:action.php

这一步要将用户输入数值与session中的数值进行比对

相等,输出“正确”

不相等,输出“不正确”

<?php
Session_start(); 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
 if($_SESSION["check"]!=intval($_POST["cikle"])){
 echo "不正确";
 }else{
 echo "正确";
 }
}

看完上述内容,你们对使用php怎么实现一个网站验证码功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. PHP实现验证码功能
  2. 使用vuejs如何实现一个验证码功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:Yii中实现分页的方法有哪些

下一篇:如何使用HTML5 Canvas制作时钟

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》