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

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

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/hmi1234/p/16184450.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!