PHP生成图形验证码
2024-08-30 17:32:02
在建站过程中,很多时候都会需要用户验证验证码等操作,比如:注册、登录、发表评论、获取资源等等,一方面可以验证当前用户的行为是否是爬虫、机器人等情况,给网站数据统计产生影响;另一方面可以防止用户大量刷取资源导致服务器资源紧张甚至宕机;现在验证码在表单中的应用越来越多了,但是如果用js来实现总觉得不太方便,因此可以使用php来实现。
测试地址:http://api.hmiwin.top/api/yzm.php
请求参数:num,text
参数说明:其中num是欲输出验证码的字符个数;text是欲输出验证码图片里面的内容
php源码如下:
<?php
//http://api.hmiwin.top/api/yzm.php
$num = $_GET['num'];
$text = $_GET['text'];
if($num=="")//如果num参数为空默认等于4
$num = 4;
check_code(150, 50, $num ,$text);//调用,其中$num是欲输出验证码的字符个数,$text是欲输出验证码图片里面的内容
function check_code($width , $height , $num , $string ,$type = 'jpeg' ) {
$img = imagecreate($width, $height);
for ($i = 0; $i < $num; $i++) {
$rand = mt_rand(0, 2);
switch($rand) {
case 0:
$ascii = mt_rand(48, 57);
break;
case 1:
$ascii = mt_rand(65, 90);
break;
case 2:
$ascii = mt_rand(97, 122);
break;
}
$string .= sprintf('%c', $ascii);
}
imagefilledrectangle($img, 0, 0, $width, $height, randBg($img));
for ($i = 0; $i < 50; $i++) {
imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), randPix($img));
}
for ($i = 0; $i < $num; $i++) {
$x = floor($width/$num) *$i + 2;
$y = mt_rand(0, $height - 15);
imagechar($img, 5, $x, $y, $string[$i], randPix($img));
}
$func = 'image' . $type;
$header = 'content-type:image/' . $type;
if (function_exists($func)) {
header($header);
$func($img);
} else {
exit('不支持');
}
imagedestroy($img);
return $string;
}
function randBg($img) {
return imagecolorallocate($img, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
}
function randPix($img) {
return imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
}
?>
欢迎转载,转载请申明来源地址!
最新文章
- ANSI Common Lisp Practice - My Answers - Chatper - 2
- equals()方法
- charles使用教程指南
- Unity手游之路<;七>;角色控制器
- [BS-12] JSON的基础知识--百科
- node.js npm权限问题try running this command again as root/Administrator.
- MVC架构学习
- Linq 查询与普通查询的区别
- python 单向链表实现
- Consumer高级特性
- Vue-移动端项目真机测试
- Eclipse maven hadoop -- java.io.IOException: No FileSystem for scheme: hdfs
- Spring源码学习(7)——AOP
- 对python的一些拙见
- day1-接口测试_jmeter_postman
- 比Python、Java更快的 Go 语言,能否称霸江湖?
- python第六十一天,第六十二天 redis
- Android Studio中依赖第三库导致support版本冲突解决方案
- VScode 安装必备
- 原生java调用webservice的方法,不用生成客户端代码