短信验证码PHP代码
- 格式:doc
- 大小:47.00 KB
- 文档页数:3
PHP简单验证码功能机制实例详解本⽂实例讲述了PHP简单验证码功能机制。
分享给⼤家供⼤家参考,具体如下:⽹站的安全性是开发者不可忽视的⼀个问题,⽬前使⽤最多的⼀种可以提⾼⽹站安全性的⽅法就是使⽤验证码功能机制,有的仅仅使⽤⼀个⼏位数字字母混乱的验证码,有的进⾏⼿机发送短信进⾏验证,有的使⽤邮箱发送邮件进⾏验证,但是这个验证码功能机制是如何实现的呢?下⾯就为⼤家详细解释验证码功能机制的实现思路以及简单的实现⽅法。
1、验证码功能机制实现思路①常规的验证码实现:a、产⽣⼀张png的图⽚b、为图⽚设置背景⾊c、设置字体颜⾊和样式d、产⽣4位数的随机的验证码e、把产⽣的每个字符调整旋转⾓度和位置画到png图⽚上f、加⼊噪点和⼲扰线防⽌注册机器分析原图⽚来恶意注册g、输出图⽚h、释放图⽚所占内存i、将验证码保存到session或是数据库j、将和输⼊的验证码进⾏对⽐②短信(邮箱)验证码机制:a、产⽣4-6位数的随机的验证码b、把产⽣的每个字符保存到session或是数据库c、将验证码发送到⽤户的⼿机(邮箱)d、⽤户在规定时间内进⾏输⼊e、将验证码从session或是数据库中取出f、将和输⼊的验证码进⾏对⽐验证2、简单的实现验证码功能机制①新建captcha.php,写⼊以下代码<?php/*** =======================================* Created by WeiBang Technology.* User: Wei ZhiHua* Date: 2016/10/12 0020* Time: 下午 4:14* Power: 实现验证码功能* =======================================*///开启sessionsession_start();//创建⼀个⼤⼩为 100*30 的验证码$image = imagecreatetruecolor(100, 30);$bgcolor = imagecolorallocate($image, 255, 255, 255);imagefill($image, 0, 0, $bgcolor);$captch_code = '';for ($i = 0; $i < 4; $i++) {$fontsize = 6;$fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));$data = 'abcdefghijkmnpqrstuvwxy3456789';$fontcontent = substr($data, rand(0, strlen($data) - 1), 1);$captch_code .= $fontcontent;$x = ($i * 100 / 4) + rand(5, 10);$y = rand(5, 10);imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);}//就⽣成的验证码保存到session$_SESSION['authcode'] = $captch_code;//在图⽚上增加点⼲扰元素for ($i = 0; $i < 200; $i++) {$pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));imagesetpixel($image, rand(1, 99), rand(1, 29), $pointcolor);}//在图⽚上增加线⼲扰元素for ($i = 0; $i < 3; $i++) {$linecolor = imagecolorallocate($image, rand(80, 220), rand(80, 220), rand(80, 220));imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1, 29), $linecolor);}//设置头header('content-type:image/png');imagepng($image);imagedestroy($image);>②新建form.php,写⼊以下代码<?php/*** =======================================* Created by WeiBang Technology.* User: Wei ZhiHua* Date: 2016/10/12 0021* Time: 下午 4:14* Power: 实现验证码功能* =======================================*/if (isset($_REQUEST['authcode'])) {session_start();if (strtolower($_REQUEST['authcode']) == $_SESSION['authcode']) {echo "输⼊正确!";} else {echo "输⼊错误!";}exit();}><!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"/><title>确认验证码</title></head><body><form method="post" action="./form.php"><p>验证码图⽚:<img id="captcha_img" border="1" src="./captcha.php?r=<?php echo rand(); ?>" width=100 height=30><a href="javascript:void(0)" rel="external nofollow"onClick="document.getElementById('captcha_img').src='./captcha.php?r='+Math.random()">换⼀个?</a></p><p>请输⼊图⽚中的内容:<input type="text" name="authcode" value=""/></p><p><input type="submit" value="提交" style="padding:6px 20px;"></p></form></body></html>以上就是php验证码的制作思路和实现⽅法,从简单到复杂,可以根据这些写出⾮常完美的验证码功能机制。
PHP如何实现验证码现在来说说简单的纯数字验证码吧。
如果是初学者,建议按照我代码的注释 //数字⼀步步来。
最简单的⽅法,还是把整个代码复制⾛了。
新建⼀个captcha.php:<?php//11>设置session,必须处于脚本最顶部session_start();/*$image = imagecreatetruecolor(100, 30); //1>设置验证码图⽚⼤⼩的函数//5>设置验证码颜⾊ imagecolorallocate(int im, int red, int green, int blue);$bgcolor = imagecolorallocate($image,255,255,255); //#ffffff//6>区域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的区域着⾊,col 表⽰欲涂上的颜⾊imagefill($image, 0, 0, $bgcolor);//10>设置变量$captcha_code = "";*///7>⽣成随机数字for($i=0;$i<4;$i++){//设置字体⼤⼩$fontsize = 6;//设置字体颜⾊,随机颜⾊$fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //0-120深颜⾊//设置数字$fontcontent = rand(0,9);//10>.=连续定义变量$captcha_code .= $fontcontent;//设置坐标$x = ($i*100/4)+rand(5,10);$y = rand(5,10);imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);}//10>存到session$_SESSION['authcode'] = $captcha_code;//8>增加⼲扰元素,设置雪花点for($i=0;$i<200;$i++){//设置点的颜⾊,50-200颜⾊⽐数字浅,不⼲扰阅读$pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));//imagesetpixel — 画⼀个单⼀像素imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor);}//9>增加⼲扰元素,设置横线for($i=0;$i<4;$i++){//设置线的颜⾊$linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220));//设置线,两点⼀线imageline($image,rand(1,99), rand(1,29),rand(1,99), rand(1,29),$linecolor);}//2>设置头部,image/pngheader('Content-Type: image/png');//3>imagepng() 建⽴png图形函数imagepng($image);//4>imagedestroy() 结束图形函数销毁$imageimagedestroy($image);接着就是静态页的代码了:index.html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>⽆标题⽂档</title></head><body><form method="post" action="./form.php"><p>验证码: <img id="captcha_img" border='1' src='./captcha.php?r=echo rand(); ?>' style="width:100px; height:30px" /><a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='./captcha.php?r='+Math.random()">换⼀个?</a> </p><P>请输⼊验证码:<input type="text" name='authcode' value=''/></p><p><input type='submit' value='提交' style='padding:6px 5px;'/></p></form></body></html>从index.html可以看到,提交的表单是到form.php的,所以还要有⼀个判断的form.php代码:<?phpheader("Content-Type:text/html;charset=utf-8"); //设置头部信息//isset()检测变量是否设置if(isset($_REQUEST['authcode'])){session_start();//strtolower()⼩写函数if(strtolower($_REQUEST['authcode'])== $_SESSION['authcode']){//跳转页⾯echo "<script language=\"javascript\">";echo "document.location=\"./form.php\"";echo "</script>";}else{//提⽰以及跳转页⾯echo "<script language=\"javascript\">";echo "alert('输⼊错误!');";echo "document.location=\"./form.php\"";echo "</script>";}exit();}显⽰页⾯如下:数字加英⽂的验证码,只需更改captcha.php页⾯中的 7》即可,其他两个页⾯不需要动,代码如下:<?php//11>设置session,必须处于脚本最顶部session_start();$image = imagecreatetruecolor(100, 30); //1>设置验证码图⽚⼤⼩的函数//5>设置验证码颜⾊ imagecolorallocate(int im, int red, int green, int blue);$bgcolor = imagecolorallocate($image,255,255,255); //#ffffff//6>区域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的区域着⾊,col 表⽰欲涂上的颜⾊imagefill($image, 0, 0, $bgcolor);//10>设置变量$captcha_code = "";//7>⽣成随机的字母和数字for($i=0;$i<4;$i++){//设置字体⼤⼩$fontsize = 8;//设置字体颜⾊,随机颜⾊$fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //0-120深颜⾊//设置需要随机取的值,去掉容易出错的值如0和o$data ='abcdefghigkmnpqrstuvwxy3456789';//取出值,字符串截取⽅法 strlen获取字符串长度$fontcontent = substr($data, rand(0,strlen($data)),1);//10>.=连续定义变量$captcha_code .= $fontcontent;//设置坐标$x = ($i*100/4)+rand(5,10);$y = rand(5,10);imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);}//10>存到session$_SESSION['authcode'] = $captcha_code;//8>增加⼲扰元素,设置雪花点for($i=0;$i<200;$i++){//设置点的颜⾊,50-200颜⾊⽐数字浅,不⼲扰阅读$pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));//imagesetpixel — 画⼀个单⼀像素imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor);}//9>增加⼲扰元素,设置横线for($i=0;$i<4;$i++){//设置线的颜⾊$linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220));//设置线,两点⼀线imageline($image,rand(1,99), rand(1,29),rand(1,99), rand(1,29),$linecolor);}//2>设置头部,image/pngheader('Content-Type: image/png');//3>imagepng() 建⽴png图形函数imagepng($image);//4>imagedestroy() 结束图形函数销毁$imageimagedestroy($image);显⽰页⾯如下:⽣成汉字类验证码,在运⾏过程中,提⽰乱码错误,⽆法显⽰,未能解决,代码如下:php//11>设置session,必须处于脚本最顶部session_start();//1>设置验证码图⽚⼤⼩的函数$image = imagecreatetruecolor(200, 60);//5>设置验证码颜⾊ imagecolorallocate(int im, int red, int green, int blue);$bgcolor = imagecolorallocate($image,255,255,255); //#ffffff//6>区域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的区域着⾊,col 表⽰欲涂上的颜⾊imagefill($image, 0, 0, $bgcolor);//7>设置ttf字体$fontface = 'FZYTK.TTF';//7>设置字库,实现简单的数字储备$str='天地不仁以万物为刍狗圣⼈不仁以百姓为刍狗这句经常出现在控诉暴君暴政上地残暴不仁把万物都当成低贱的猪狗来看待⽽那些⾼⾼在上的所谓圣⼈们也没两样还不是把我们⽼百姓也当成猪狗不如的东西但实在正取的解读是地不情感⽤事对万//str_split()切割字符串为⼀个数组,⼀个中⽂在utf_8为3个字符$strdb = str_split($str,3);//>11$captcha_code = '';//8>⽣成随机的汉⼦for($i=0;$i<4;$i++){//设置字体颜⾊,随机颜⾊$fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //0-120深颜⾊//随机选取中⽂$in = rand(0,count($strdb));$cn = $strdb[$in];//将中⽂记录到将保存到session的字符串中$captcha_code .= $cn;/*imagettftext (resource $image ,float $size ,float $angle ,int $x ,int $y,int $color,string $fontfile ,string $text ) 幕布,尺⼨,⾓度,坐标,颜⾊,字体路径,⽂本字符串mt_rand()⽣成更好的随机数,⽐rand()快四倍*/imagettftext($image, mt_rand(20,24),mt_rand(-60,60),(40*$i+20),mt_rand(30,35),$fontcolor,$fontface,$cn);}//11>存到session$_SESSION['authcode'] = $captcha_code;//9>增加⼲扰元素,设置点for($i=0;$i<200;$i++){//设置点的颜⾊,50-200颜⾊⽐数字浅,不⼲扰阅读$pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200)); //imagesetpixel — 画⼀个单⼀像素imagesetpixel($image, rand(1,199), rand(1,59), $pointcolor);}//10>增加⼲扰元素,设置线for($i=0;$i<4;$i++){//设置线的颜⾊$linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220));//设置线,两点⼀线imageline($image,rand(1,199), rand(1,59),rand(1,199), rand(1,59),$linecolor);}//2>设置头部,image/pngheader('Content-Type: image/png');//3>imagepng() 建⽴png图形函数imagepng($image);//4>imagedestroy() 结束图形函数销毁$imageimagedestroy($image);。
php手机短信验证代码(共9篇)篇一:短信验证码PHP代码篇二:用维泰SDK实现发送短信验证码php源码phprequire "httprequest.php";/*' 该示范程序通过:88/ 发送短信''返回值:'返回值大于0表示成功,小于0表示失败。
如果失败,返回信息还包括失败原因的文字描述。
'说明:'返回成功仅表示服务器已经成功接收客户提交的任务,并不表示对方已经收到短信。
'因移动公司对短信内容审核严格,如测试未收到,请及时联系客服'请不要发送"测试","你好","abc"等无意义的内容*/function smsend($strMobile,$strText){//发送短信的服务器地址$strServerURL = ":88/cgi/sendsmsbatch.asp";// 短信账号:免费申请,如有问题请联系QQ732055019// :88/mis/user_reg_form.asp?interest=sms.api $strUser= "username";// 验证密码: 初始密码由平台通过短信发送, 用户可登录平台自己修改$strPass= "userpass";if($strUser==""){echo ("短信帐号没有设定!");return;}if($strPass==""){echo ("短信验证密码没有设定!");return;}if($strMobile==""){echo ("短信接收号码无效!");return;}if($strText=="undefined|| $strText==""){echo ("短信内容不能为空!");return;}if(strlen($strText)69){echo ("短信内容不能超过69个字");return;}//准备表单:使用urlencode对参数进行编码,字符集gb2312 $strForm = "User=. urlencode($strUser);$strForm .= "&Pass=. urlencode($strPass);$strForm .= "&Mobile=. urlencode($strMobile);$strForm .= "&Text=. urlencode($strText);$h= new HttpRequest();$s= $h-request("GET",$strServerURL."?".$strFor m,"");if (strpos($s,"SUCCESS")===false){//出现错误echo ("短信通知发送失败!br.$s);}else {//发送成功echo("短信通知发送成功!");}}htmlheadtitle发送短信通知/titlemeta http-equiv="Content-Typecontent="text/html; charset=gb2312"/headbodybrdiv class="title1"发送短信通知/divdiv class="content1"$strMobile="132****9999";//接收短信的手机号码 $strText="Test SMS";//短信内容(不要超过69个字) smsend($strMobile,$strText);/div/body/htmlphp //httprequest.phpclass HttpRequest{var $_host;var $_uri;var $_port;var $_response;function parseURL($url){$req = $url;$pos = strpos($req, '://');$this-_protocol = strtolower(substr($req, 0, $pos));$req = substr($req, $pos+3);$pos = strpos($req, '/');if($pos === false)$pos = strlen($req);$host = substr($req, 0, $pos);if(strpos($host, ':') === false){$this-_host = $host;$this-_port = ($this-_protocol == 'https') ? 443 : 80;}else{list($this-_host, $this-_port) = explode(':', $host);}$this-_uri = substr($req, $pos);if($this-_uri == '')$this-_uri = '/';}function request($method , $url, $sPostData){$this-parseURL($url);$fp = pfsockopen( $this-_host, $this-_port, &$errno, &$errstr, 120); if( !$fp ) {echo "$errstr ($errno)br\n";return "";}if( strtoupper($method) == "GET"){fputs( $fp, "GET ".$this-_uri.HTTP/1.0\r\n"); }else if( strtoupper($method) == "POST) {fputs( $fp, "POST ".$this-_uri.HTTP/1.0\r\n"); }fputs( $fp, "Accept: */*\n");fputs( $fp, "Host: ".$this-_host."\r\n");fputs( $fp, "Connection: Close\r\n");if( strtoupper($method) == "POST) {$strlength = strlen( $data);fputs( $fp, "Content-type:application/x-www-form-urlencoded\r\n); fputs( $fp, "Content-length: ".$strlength."\r\n");fputs($fp, "\r\n");fputs( $fp, $data."\r\n");}else{fputs($fp, "\r\n");}$this-_response = "";while( !feof( $fp ) ) {$this-_response .= fgets( $fp, 4096);}fclose( $fp);$s = $this-getResponseBody();return $s;}function getResponse(){return $this-_response;}function getResponseBody(){$sKey = "\r\n\r\n";$pos = strpos($this-_response,$sKey);if($pos===false) return "";$str= substr($this-_response,$pos + 4);return $str;}}篇三:用免费短信验证码SDK实现手机注册验证功能用免费短信验证码SDK实现手机注册验证功能第一步获取短信SDK请到Mob官网下载最新版本的SDK,下载回来后解压,可以看到下面的文件结构:其中SMS_SDK.framework 为依赖库文件SMS_SDKDemo 为示例demo ,其中保存了短信SDK的演示项目代码。
php验证码代码怎么写php验证码代码怎么写我们先来处理php程序文件的'开始符和结束符,这个不太复杂,我们用两个变量来表示它们:复制代码代码如下:<?php//文件头...header("Content-type:image/png");//创建真彩色白纸$im=@imagecreatetruecolor(50,20)ordie("建立图像失败");//获取背景颜色$background_color=imagecolorallocate($im,255,255,255);//填充背景颜色(这个东西类似油桶)imagefill($im,0,0,$background_color);//获取边框颜色$border_color=imagecolorallocate($im,200,200,200);//画矩形,边框颜色200,200,200imagerectangle($im,0,0,49,19,$border_color);//逐行炫耀背景,全屏用1或0for($i=2;$i<18;$i++){//获取随机淡色$line_color=imagecolorallocate($im,rand(200,255),rand(200, 255),rand(200,255));//画线imageline($im,2,$i,47,$i,$line_color);}//设置字体大小$font_size=12;//设置印上去的文字$Str[0]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";$Str[1]="abcdefghijklmnopqrstuvwxyz";$Str[2]="01234567891234567890123456";//获取第1个随机文字$imstr[0]["s"]=$Str[rand(0,2)][rand(0,25)];$imstr[0]["x"]=rand(2,5);$imstr[0]["y"]=rand(1,4);//获取第2个随机文字$imstr[1]["s"]=$Str[rand(0,2)][rand(0,25)];$imstr[1]["x"]=$imstr[0]["x"]+$font_size-1+rand(0,1);$imstr[1]["y"]=rand(1,3);//获取第3个随机文字$imstr[2]["s"]=$Str[rand(0,2)][rand(0,25)];$imstr[2]["x"]=$imstr[1]["x"]+$font_size-1+rand(0,1);$imstr[2]["y"]=rand(1,4);//获取第4个随机文字$imstr[3]["s"]=$Str[rand(0,2)][rand(0,25)];$imstr[3]["x"]=$imstr[2]["x"]+$font_size-1+rand(0,1);$imstr[3]["y"]=rand(1,3);//写入随机字串for($i=0;$i<4;$i++){//获取随机较深颜色$text_color=imagecolorallocate($im,rand(50,180),rand(50,1 80),rand(50,180));//画文字imagechar($im,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imst r[$i]["s"],$text_color);}//显示图片imagepng($im);//销毁图片imagedestroy($im);> </p【php验证码代码怎么写】。
python实现短信验证码发送1、短信⽹关model1# -*- coding: utf-8 -*-2from__future__import unicode_literals34from django.db import models5from django.template import Context6from django.template import Template as DjangoTemplate7from django.utils.safestring import mark_safe8from django.utils.translation import ugettext_lazy as _9import json10import requests1112# Create your models here.13class SmsSendingProfile(models.Model):14 TYPE_CHOICES = (15 ('common', '管理'),16 ('phish', '钓鱼')17 )18"""短信⽹关:包括以下属性(短信⽹关名称,⽹关URL,请求参数,⽤途)"""19 name = models.CharField(max_length=100, verbose_name='名称', help_text='短信⽹关名称,必填,最多100个字符')20 url = models.CharField(max_length=2083, verbose_name='⽹关URL', help_text='⽹关URL,必填,最多2083个字符') # IE limit URL length to 208321 params = models.TextField(max_length=5000, verbose_name='请求参数', help_text='请求参数,必填,最多5000个字符')2223 type = models.CharField(_('⽤途'), choices=TYPE_CHOICES, max_length=15, default='common', help_text='请选择⽤途')2425def test(self, send_to, content):26'''27测试28 :param send_to: 发送⾄29 :param content: 邮件内容30 :return: ⽆返回值31'''32if not send_to:33raise Exception('未指定⼿机号码')34if content.strip() == '':35 content = '【红⼭瑞达】这是⼀条测试短信,发送⾃意识测评系统。
用php生成带有雪花背景的验证码用php生成带有雪花背景的验证码用php生成带有雪花背景的验证码,有需要的朋友可以参考下。
以下代码,有详细的注释,方便学习。
就跟随店铺一起去了解下吧,想了解更多相关信息请持续关注我们店铺!<?session_start();?><FORM METHOD=POST ACTION=""><input type=text name=number maxlength=4><img src="YanZhengMa.php?act=init"><INPUT TYPE="submit" name="sub"></FORM><?//检验校验码if(isset($HTTP_POST_VARS["sub"])):if($HTTP_POST_VARS["number"] != $HTTP_SESSION_VARS[login_check_number] || empty($HTTP_POST_VARS["number"])){echo "校验码不正确!" ;}else{echo"验证码通过!";}endif;show_source('test.php');//以上本页的源码//以下是生成验证码的源码show_source('YanZhengMa.php');><?phpsession_start();session_register("login_check_number");//昨晚看到了chianren上的验证码效果,就考虑了一下,用PHP 的GD库完成了类似功能//先成生背景,再把生成的验证码放上去$img_height=120; //先定义图片的长、宽$img_width=40;if($HTTP_GET_VARS["act"]== "init"){//srand(microtime() * 100000);//PHP420后,srand不是必须的for($Tmpa=0;$Tmpa<4;$Tmpa++){$nmsg.=dechex(rand(0,15));}//by sports98$HTTP_SESSION_VARS[login_check_number] = $nmsg;//$HTTP_SESSION_VARS[login_check_number] = strval(mt_rand("1111","9999")); //生成4位的随机数,放入session中//谁能做下补充,可以同时生成字母和数字啊??----由sports98完成了$aimg = imageCreate($img_height,$img_width); //生成图片ImageColorAllocate($aimg, 255,255,255); //图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了$black = ImageColorAllocate($aimg, 0,0,0); //定义需要的.黑色ImageRectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//先成一黑色的矩形把图片包围//下面该生成雪花背景了,其实就是在图片上生成一些符号for ($i=1; $i<=100; $i++) { //先用100个做测试imageString($aimg,1,mt_rand(1,$img_height),mt_rand(1,$im g_width),"*",imageColorAllocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));//哈,看到了吧,其实也不是雪花,就是生成*号而已。
PHP开发调⽤阿⾥云短信验证码的代码-直接可⽤1:最低要求 PHP 5.62:安装了composer3:阿⾥云composer镜像地址命令(如果设置过就不需要):composer config -g repo.packagist composer https:///composer/4:安装 SDK 核⼼库 OpenAPI : Alibaba Cloud SDK for PHP 作为依赖项:composer require alibabacloud/darabonba-openapi5:阿⾥云短信SDK安装包命令(官⽅地址:https:///api-tools/sdk/Dysmsapi):composer require alibabacloud/dysmsapi-20170525 2.0.8<?php// This file is auto-generated, don't edit it. Thanks.namespace lib;use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;use Darabonba\OpenApi\Models\Config;class aliyunSms{private static $accessKeyId = 'LTAI5t7AC3RH3333pZTDCaA3';//accessKeyIdprivate static $accessKeySecret = 'ihDUcyqNZvNYXASfLtijI33333NSk';//accessKeySecretprivate static $signName = 'xxxx技有限公司';//签名private static $templateCode = 'SMS_228533331';//模板代码/*** 使⽤AK&SK初始化账号Client* @param string $accessKeyId* @param string $accessKeySecret* @return Dysmsapi Client*/private static function createClient($accessKeyId, $accessKeySecret){$config = new Config([// 您的AccessKey ID"accessKeyId" => $accessKeyId,// 您的AccessKey Secret"accessKeySecret" => $accessKeySecret]);// 访问的域名$config->endpoint = "";return new Dysmsapi($config);}/*** @param string $phoneNumbers ⼿机号* @param string $code 验证码* @return void*/// public static function main($args)private static function main($phoneNumbers, $code){$client = self::createClient(self::$accessKeyId, self::$accessKeySecret);$sendSmsRequest = new SendSmsRequest(["templateParam" => "{\"code\":\"{$code}\"}","phoneNumbers" => "{$phoneNumbers}","signName" => self::$signName,"templateCode" => self::$templateCode]);$ali_res = $client->sendSms($sendSmsRequest);if ($ali_res->body->code == 'OK' && $ali_res->body->bizId != NULL) {return true;}switch ($ali_res->body->code) {case 'isv.BUSINESS_LIMIT_CONTROL':exception('短信发送频繁,请稍候再试');//tp的抛出错误,换成你⾃⼰的报错break;case 'isv.TEMPLATE_PARAMS_ILLEGAL':exception('短信验证码不符合变量规范');//tp的抛出错误,换成你⾃⼰的报错break;case 'isv.MOBILE_NUMBER_ILLEGAL':exception('⼿机号不正确,⽆法发送短信');//tp的抛出错误,换成你⾃⼰的报错break;}//少见的错误,记录下来//log_err($ali_res->body, '发送短信发⽣错误', 'ali_sms');//换成你的exception($ali_res->body->message);//tp的抛出错误,换成你⾃⼰的报错// 以下是阿⾥云短信正确和失败返回的数据,以作参考// 失败演⽰返回数据/* object(AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponseBody)#81 (6) {["bizId"] => NULL["code"] => string(24) "isv.SMS_TEMPLATE_ILLEGAL"["message"] => string(38) "模板不合法(不存在或被拉⿊)"["requestId"] => string(36) "21A90D61-2D5E-533D-BFE7-9D16F8312A0E"["_name":protected] => array(4) {["bizId"] => string(5) "BizId"["code"] => string(4) "Code"["message"] => string(7) "Message"["requestId"] => string(9) "RequestId"}["_required":protected] => array(0) {}}*/// 成功返回数据演⽰/* object(AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponseBody)#81 (6) {["bizId"] => string(20) "839015438514162136^0"["code"] => string(2) "OK"["message"] => string(2) "OK"["requestId"] => string(36) "EA37C2B7-E427-59F8-8B7C-06AD846A5439"["_name":protected] => array(4) {["bizId"] => string(5) "BizId"["code"] => string(4) "Code"["message"] => string(7) "Message"["requestId"] => string(9) "RequestId"}["_required":protected] => array(0) {}}*/}//发短信public static function sendSms($phoneNumbers, $code){$res = self::main($phoneNumbers, $code);return $res;}}此代码只需要修改命名空间和阿⾥云accessKeyId等相关信息,即可使⽤~exception是TP的错误异常抛出,我是做了全局的异常托管,并且在所有报错的地⽅调⽤此⽅法就能终端代码,报出错误,你只需要换成你的中断代码返回错误即可。
PHP验证码如何生成类完整代码清源分享给大家的这款php验证码生成类灵活好用,用户可以定义各个成员有宽、高、画布、字数、类型、画类型同时我们只要修改 $Type就可以定义生成的是纯数字 , 纯小写字母,大小写数字混合,有需要的朋友可以借鉴参考。
代码:<?phpclass Code{// 1. 定义各个成员有宽、高、画布、字数、类型、画类型private $width; //宽度private $height; //高度private $num; //验证码字数private $imgType; //生成图片类型private $Type; //字串类型 1,2,3 三个选项 1 纯数字 2 纯小写字母 3 大小写数字混合private $hb; //画布public $codestr; // 验证码字串public function __construct($height=20,$num=4,$imgType="jpeg",$Type=1){$this->width = $num*20;$this->height = $height;$this->num = $num;$this->imgType = $imgType;$this->Type = $Type;$this->codestr = $this->codestr();$this->zuhe();}// 2. 定义随机获取字符串函数private function codestr(){switch($this->Type){case 1: // 类型为1 获取1-9随机数$str = implode("",array_rand(range(0,9),$this->num));break;case 2: // 类型为2 获取a-z随机小写字母$str = implode("",array_rand(array_flip(range(a,z)),$this->num));break;(PS:T不错的PHP Q扣峮:276167802,验证:wk)case 3: // 类型为3 获取数字,小写字母,大写字母混合for($i=0;$i<$this->num;$i++){$m = rand(0,2);switch($m){case 0:$o = rand(48,57);break;case 1:$o = rand(65,90);break;case 2:$o = rand(97,122);break;}$str .= sprintf("%c",$o);}break;}return $str;}// 3. 初始化画布图像资源private function Hb(){$this->hb = imagecreatetruecolor($this->width,$this->height);}// 4. 生成背景颜色private function Bg(){return imagecolorallocate($this->hb,rand(130,250),rand(130,250),rand(130,250));}// 5. 生成字体颜色private function Font(){return imagecolorallocate($this->hb,rand(0,100),rand(0,100),rand(0,100));}// 6. 填充背景颜色private function BgColor(){imagefilledrectangle($this->hb,0,0,$this->width,$this->height,$this->Bg());}// 7. 干扰点private function ganrao(){$sum=floor(($this->width)*($this->height)/3);for($i=0;$i<$sum;$i++){imagesetpixel($this->hb,rand(0,$this->width),rand(0,$this->height),$this->Bg());}}// 8. 随机直线弧线private function huxian(){for($i=0;$i<$this->num;$i++){imageArc($this->hb,rand(0,$this->width),rand(0,$this->height),rand(0,$this->width),rand( 0,$this->height),rand(0,360),rand(0,360),$this->Bg());}}// 9. 写字private function xiezi(){for($i=0;$i<$this->num;$i++){$x=ceil($this->width/$this->num)*$i;$y=rand(1,$this->height-15);imagechar($this->hb,5,$x+4,$y,$this->codestr[$i],$this->Font());}}// 10. 输出private function OutImg(){$shuchu="image".$this->imgType;$header="Content-type:image/".$this->imgType;if(function_exists($shuchu)){header($header);$shuchu($this->hb);}else{exit("GD库没有此类图像");}}// 11. 拼装private function zuhe(){$this->Hb();$this->BgColor();$this->ganrao();$this->huxian();$this->xiezi();$this->OutImg();}public function getCodeStr(){return $this->codestr;}}?>来源:清源教育。
python实现发送和获取⼿机短信验证码⾸先为⼤家分享python实现发送⼿机短信验证码后台⽅法,供⼤家参考,具体内容如下1、⽣成4位数字验证码def createPhoneCode(session):chars=['0','1','2','3','4','5','6','7','8','9']x = random.choice(chars),random.choice(chars),random.choice(chars),random.choice(chars)verifyCode = "".join(x)session["phoneVerifyCode"] = {"time":int(time.time()), "code":verifyCode}return verifyCode2、发送给外部短信接⼝(post⽅式)def sendTelMsg(msg, phoneID):SendTelMsgUrl="/jk.aspx"params = {"zh":"china", "mm":"china@10086","hm":phoneID,"nr":msg,"sms_type":88}postData=urllib.urlencode(params)req = urllib2.Request(SendTelMsgUrl, postData)req.add_header('Content-Type', "application/x-www-form-urlencoded")respone = urllib2.urlopen(req)res = respone.read()return res其中session参数是django urls.py 后台⽅法以request.session传⼊3、前端js$("button[name=getVerifyBt]").bind("click", function(){var self = this;var userPhoneEl = $("input[name=phoneNum]");var userPhone = $.trim(userPhoneEl.val());if (userPhone == ""){alert("请填写号码!");return;}$.get("/getPhoneVerifyCode/"+userPhone + "/").success(function(msg){(msg);var ddEl = $(self).siblings("dd.showTag");if(msg == "ok"){ddEl.find("span").hide();ddEl.find("span[name=success]").show();}else{ddEl.find("span").hide();ddEl.find("span[name=error]").show();}}).error(function(msg){(msg);});var step = 60;$(this).attr("disabled", true);$(this).html("重新发送"+step);var interThread = setInterval(function(){step-=1;$(self).html("重新发送"+step);if(step <=0){$(self).removeAttr("disabled");$(self).html("获取验证码");clearInterval(interThread);}}, 1000);});下⾯就为⼤家介绍python解决接⼝测试获取⼿机验证码问题的⽅法:最近在做接⼝测试的时候遇到⼀个问题,就是有个很重要的接⼝要⽤到⼿机短信验证码,⽽其他接⼝都依赖于这个验证码,如果没有短信验证码就不能进⾏下⾯接⼝的测试,所以为了定时的验证线上的接⼝是否正常,⽽且⼜不修改代码,所以就想到以下解决⽅案,如果⼤家有了更好⽅案可以⼀起交流分享。