通过原生js封装一个获取n位随机验证码的函数.

纯原生js封装随机验证码函数,拿走即用.

function getCode(num){

        //  num:生成num位验证码

        // 定义一个验证码库

        var library = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'

        // 声明一个空字符串用来存放验证码

        var str = '  ';

        // 使用循环来取每一个验证码  

        for (var i = 0; i < num; i++){

                // 声明一个变量用来存放其中的一个验证码

                var a = Math.floor(Math.random()*(library.length - 0) + 0);

                // 将获取到的验证码追加到空字符串中

                str += library.charAt(a);

};

// 设置返回值  将验证码返回

return str;

};

// 调用函数

var s = getCode(5);

console.log(s);
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的原生PHP验证码类的示例: ```php class Captcha { // 验证码字符长度 protected $length = 4; // 验证码宽度 protected $width = 100; // 验证码高度 protected $height = 40; // 验证码字符集 protected $charset = '0123456789'; // 验证码图片 protected $image; // 构造函数 public function __construct() { $this->create(); } // 生成验证码 public function create() { $this->image = imagecreatetruecolor($this->width, $this->height); $bgColor = imagecolorallocate($this->image, 255, 255, 255); imagefill($this->image, 0, 0, $bgColor); $code = $this->generateCode(); $textColor = imagecolorallocate($this->image, 0, 0, 0); $font = __DIR__ . '/arial.ttf'; for ($i = 0; $i < $this->length; $i++) { $x = ($this->width - 20) / $this->length * $i + 10; $y = $this->height / 2 + 10; imagettftext($this->image, 20, rand(-10, 10), $x, $y, $textColor, $font, $code[$i]); } header('Content-Type: image/png'); imagepng($this->image); } // 验证码校验 public function check($code) { if (strtolower($code) == strtolower($_SESSION['captcha'])) { return true; } else { return false; } } // 生成随机字符 protected function generateCode() { $code = ''; $charsetLength = strlen($this->charset); for ($i = 0; $i < $this->length; $i++) { $code .= $this->charset[rand(0, $charsetLength - 1)]; } $_SESSION['captcha'] = $code; return $code; } // 析构函数 public function __destruct() { imagedestroy($this->image); } } ``` 使用示例: ```php $captcha = new Captcha(); ``` 这将生成一个验证码图像并将其输出到浏览器。要检查用户输入的验证码是否正确,可以调用`check()`方法: ```php if ($captcha->check($_POST['captcha'])) { // 验证码正确 } else { // 验证码错误 } ``` 请注意,此示例仅用于演示目的。在实际应用程序中,您可能需要添加其他功能(例如:检查用户是否已经提交了表单,以防止滥用)并进行更多的安全检查。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

关耳也要加油呐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值