验证码的php代码
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验证码

$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; break;
case 'NUMBER':
$chars='0123456789'; break;
imagefill($img, 0, 0, $backcolor);
//画线
imageline($img, mt_rand(0,$intwidth/3), mt_rand(0,$intheight/3), mt_rand($intwidth/3,$intwidth), mt_rand($intheight/3,$intheight), $fontcolor);
$randval .= chr($randstr);//chr()返回相对应于 ascii 所指定的单个字符。
//$randval .= mt_rand(0, 9);
}
}
$_SESSION["randval"] = $randval;
$intheight = 18;//验证码背景图的高
$string="";
while(strlen($string)<$len)
$string.=substr($chars,(mt_rand()%strlen($chars)),1);
return $string;
}
?>
//产生随机字符串
function randStr($len=6,$format='ALL') {
switch($format) {
php验证码实例

php验证码实例
一、概述
验证码(CAPTCHA)是一种用于验证用户是否为人类的技术,通过向用户显示一些扭曲的字符或完成一些图像识别任务来确保不是机器人提交表单。
在PHP中,我们可以使用GD库来创建自定义的验证码。
本文将介绍一个简单的PHP验证码实例,包括生成验证码图像、验证用户输入和防止验证码被恶意破解的方法。
二、准备工作
在开始之前,请确保你的PHP环境已启用GD库。
你可以通过在PHP配置文件(php.ini)中取消注释以下行来启用GD库:
然后重启Web服务器以使更改生效。
三、验证码生成
下面是一个简单的PHP验证码生成示例代码:
在上述代码中,我们使用GD库创建了一个指定宽度和高度的空白图像,并随机生成了一些扭曲的字符。
我们使用imagettftext函数将字符绘制到图像上,并使用imagepng函数将图像输出为PNG格式。
最后,我们使用imagedestroy函数销毁图像资源。
你可以根据需要调整代码中的参数,例如更改验证码长度、字体样式等。
四、验证码验证与防止恶意破解
在生成验证码后,我们需要验证用户输入的验证码是否正确。
以下是一个简单的验证码验证示例代码:。
PHP实现随机数字、字母的验证码功能

PHP实现随机数字、字母的验证码功能 可⾃定义⽣成验证码⽂字的⼤⼩、数量、⼲扰项等等,也可以⾃定义验证⽂字的字体。
废话不多说,直接上代码:1、classgd.class.php<?phpClass Captcha{private $_fontfile='';private $_size=36;private $_width=200;private $_height=100;private $_length=4;private $_image=null;private $_snow=0;private $_pixel=0;private $_line=0;public function __construct($config=array()){if(is_array($config)&&count($config)>0){if(isset($config['fontfile'])&&is_file($config['fontfile'])&&is_readable($config['fontfile'])){$this->_fontfile=$config['fontfile'];}else{return false;}if(isset($config['size'])&&$config['size']>0){$this->_size=(int)$config['size'];}if(isset($config['width'])&&$config['width']>0){$this->_width=(int)$config['width'];}if(isset($config['height'])&&$config['height']>0){$this->_height=(int)$config['height'];}if(isset($config['length'])&&$config['length']>0){$this->_length=(int)$config['length'];}if(isset($config['snow'])&&$config['snow']>0){$this->_snow=(int)$config['snow'];}if(isset($config['pixel'])&&$config['pixel']>0){$this->_pixel=(int)$config['pixel'];}if(isset($config['line'])&&$config['line']>0){$this->_line=(int)$config['line'];}$this->_image=imagecreatetruecolor($this->_width,$this->_height);return $this->_image;}else{return false;}}public function getCaptcha(){$white=imagecolorallocate($this->_image,255,255,255);imagefilledrectangle($this->_image,0,0,$this->_width,$this->_height,$white);$str=$this->_generateStr($this->_length);if(false===$str){return false;}$fontfile=$this->_fontfile;for($i=0;$i<$this->_length;$i++){$size=$this->_size;$angle=mt_rand(-30,30);$x=ceil($this->_width/$this->_length)*$i+mt_rand(5,10);$y=ceil($this->_height/1.5);$color=$this->_getRandColor();//针对中⽂字符截取//$text=mb_substr($str,$i,1,'utf-8');$text=$str{$i};imagettftext($this->_image, $size, $angle, $x, $y, $color, $fontfile, $text);}if($this->_snow){$this->_getSnow();}else{if($this->_pixel){$this->_getPixel();}if($this->_line){$this->_getLine();}}header('content-type:image/png');imagepng($this->_image);imagedestroy($this->_image);return strtolower($str);}private function _getSnow(){for($i=1;$i<=$this->_snow;$i++){imagestring($this->_image,mt_rand(1,5),mt_rand(0,$this->_width),mt_rand(0,$this->_height),'*',$this->_getRandColor());}}private function _getPixel(){for($i=1;$i<=$this->_pixel;$i++){imagesetpixel($this->_image,mt_rand(0,$this->_width),mt_rand(0,$this->_height),$this->_getRandColor());}}private function _getLine(){for($i=1;$i<=$this->_line;$i++){imageline($this->_image,mt_rand(0,$this->_width),mt_rand(0,$this->_height),mt_rand(0,$this->_width),mt_rand(0,$this->_height),$this->_getRandColor()); }}private function _generateStr($length=4){if($length<1 || $length>30){return false;}$chars=array('a','b','c','d','e','f','g','h','k','m','n','p','x','y','z','A','B','C','D','E','F','G','H','K','M','N','P','X','Y','Z',1,2,3,4,5,6,7,8,9);$str=join('',array_rand(array_flip($chars),$length));return $str;}private function _getRandColor(){return imagecolorallocate($this->_image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));}}>2、testCaptcha.php<?phprequire_once 'classgd.class.php';$config=array('fontfile'=>'fonts/simfang.ttf', //引⼊字体⽂件//'snow'=>50,'pixel'=>100,'line'=>10);$captcha=new Captcha($config);$captcha->getCaptcha();>总结以上所述是⼩编给⼤家介绍的PHP实现随机数字、字母的验证码功能,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
php手机短信验证代码(共9篇)

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程序文件的'开始符和结束符,这个不太复杂,我们用两个变量来表示它们:复制代码代码如下:<?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验证码代码怎么写】。
用php生成带有雪花背景的验证码

用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开发调用阿里云短信验证码的代码-直接可用

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的错误异常抛出,我是做了全局的异常托管,并且在所有报错的地⽅调⽤此⽅法就能终端代码,报出错误,你只需要换成你的中断代码返回错误即可。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
验证码的php代码;
<?
session_start();
$ts = time();
include("connent code.php")
?>
<!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=gb2312" />
<title>无标题文档</title>
</head>
<body>
<?php
if(isset($_POST["button"])){
if (isset($_POST['code']))
if(md5(strtoupper($_POST['code'])) !== $_SESSION['__img_code__']) {
echo "<script>alert('验证码输入错误!');history.back()</script>";
exit();
}
?>
<?php
$username=$_POST["username"];
$pw1=$_POST["pw1"];
$pw2=$_POST["pw2"];
if ($pw1!=$pw2)
{
echo"<script>alert('两次密码不一致!');history.back();</script>";
exit();
}
$sex=$_POST["sex"];
$xh=$_POST["xh"];
$bj=$_POST["bj"];
echo"你的用户名是:".$username.";
你的密码是:$pw1 ;
你的确认密码是:$pw2 ;
你的性别是:$sex ;
你的出生年月是:$date1-$date2-$date3 ;
你的爱好是:$f1 ;
你的自我简介是:$intro 。
";
$sql="select * from yonghu where yhm='".$username."'";
$q=mysql_query($sql,$conn);
$info=mysql_fetch_array($q);
if($info){
echo "<script>alert('此用户名已有');history.back();</script>";
mysql_close();
exit();
}
mysql_close();
$sql="insert into
yonghu (yhm,mma,sex,xuehao,banji)
values ('$username','$pw1','$sex','$xh','$bj')";
echo $sql;
echo "<br>";
//exit;
$result=mysql_query($sql,$conn);
echo mysql_error();
echo $result;
//exit;
if ($result)
{
echo"<script>alert('注册成功!');location.herf='denglu.php';</script>";
//mysql_close();
exit();
}
else
{
echo"<script>alert('注册失败!');location.herf='zhuce.php';</script>";
}
}
?>
</body>
</html>。