在建站过程中,很多时候都会需要用户验证验证码等操作,比如:注册、登录、发表评论、获取资源等等,一方面可以验证当前用户的行为是否是爬虫、机器人等情况,给网站数据统计产生影响;另一方面可以防止用户大量刷取资源导致服务器资源紧张甚至宕机;现在验证码在表单中的应用越来越多了,但是如果用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));
}
?>

欢迎转载,转载请申明来源地址!

最新文章

  1. ANSI Common Lisp Practice - My Answers - Chatper - 2
  2. equals()方法
  3. charles使用教程指南
  4. Unity手游之路&lt;七&gt;角色控制器
  5. [BS-12] JSON的基础知识--百科
  6. node.js npm权限问题try running this command again as root/Administrator.
  7. MVC架构学习
  8. Linq 查询与普通查询的区别
  9. python 单向链表实现
  10. Consumer高级特性
  11. Vue-移动端项目真机测试
  12. Eclipse maven hadoop -- java.io.IOException: No FileSystem for scheme: hdfs
  13. Spring源码学习(7)——AOP
  14. 对python的一些拙见
  15. day1-接口测试_jmeter_postman
  16. 比Python、Java更快的 Go 语言,能否称霸江湖?
  17. python第六十一天,第六十二天 redis
  18. Android Studio中依赖第三库导致support版本冲突解决方案
  19. VScode 安装必备
  20. 原生java调用webservice的方法,不用生成客户端代码

热门文章

  1. 在 WinForms 项目中使用全局快捷键
  2. Nginx实战|Nginx健康检查
  3. 文件传输协议:FTP、TFTP、SFTP有什么区别?
  4. 关于div及display
  5. JavaScript中if语句优化和部分语法糖小技巧推荐
  6. monit 命令详解(monit)
  7. WC2019
  8. mybatis if判断等于某个字符串
  9. Code Forces 1367A Sorting Parts 题解
  10. FlinkSQL 之乱序问题