1. 程式人生 > 其它 >php發驗證碼

php發驗證碼

php實現傳送驗證碼功能的方法:1、建立好HTML和js檔案;2、建立“Msm.php”檔案,內容為“public function sendmsm(){...}”;3、通過CURL傳送HTTP請求即可。
本文操作環境:Windows7系統、PHP7.1版、DELL G3電腦
php怎麼實現傳送驗證碼的功能?
PHP實現傳送簡訊驗證碼:
一、html程式碼

手機號碼:
手機號碼
驗證碼:
簡訊驗證碼
獲取驗證碼
二、js程式碼
/**
* 傳送驗證碼
* @return {[type]} [description]
*/
function get_svg() {
var phone = $("input[name='telephone']").val();
if (!(/^1[34578]\d{9}$/.test(phone))) {
layer.msg("請正確輸入手機號!");
return false;
}
var url = "/msm/sendmsm/phone/" + phone;
$.get(url, function (resdata) {
console.log(resdata);
layer.msg(resdata.data);
if (resdata.type == 1) {
$(".code_btn").attr('onclick', "return false;");
listion_sendmsm();
}
})
return false;
}
function listion_sendmsm() {
var time = 61;
setTime = setInterval(function () {
if (time <= 1) {
clearInterval(setTime);
$(".code_btn").text("再發一次");
$(".code_btn").attr('onclick', "return get_svg();");
return;
}
time--;
$(".code_btn").text(time + "s");
}, 1000);
}
三、PHP程式碼實現
Msm.php
/**
* 傳送簡訊
* @author
* @return [type] [description]
*/
public function sendmsm()
{
$phone = input('phone');
if(!$phone){
return WPreturn('請輸入手機號碼!',-1);
}
$code = rand(1000,9999);
$_SESSION['code'] = $code;
$res = sendmessage($code ,$phone);
if($res){
return WPreturn('傳送成功',1);
}else{
return WPreturn('傳送驗證碼失敗!',-1);
}
}
/* *
* 類名:ChuanglanSmsApi
* 功能:創藍簡訊介面請求類
* 詳細:構造創藍簡訊介面請求,獲取遠端HTTP資料
* 說明:
* 以下程式碼只是樣例程式碼,使用第三方創藍髮送簡訊介面。
* 該程式碼僅供學習,只是提供一個參考。
*/
public function sendmessage($code, $telephone)
{
$conf = getconf('');
if(!$code){
return false;
}
if(!$telephone){
return false;
}
$content = "您的驗證碼是:{$code},如非本人操作,請忽略此簡訊。";
//創藍介面引數
$postArr = array (
'account' => $conf['msm_appkey'],
'password' => $conf['msm_secretkey'],
'msg' => urlencode($content),
'phone' => $telephone,
'report' => true
);
$result = $this->curlPost("http://smssh1.253.com/msg/send/json", $postArr);
$json = json_decode($result);
if($json -> code != 0){
return false;
}else{
return true;
}
}
/**
* 通過CURL傳送HTTP請求
* @param string $url //請求URL
* @param array $postFields //請求引數
* @return mixed
*
*/
private function curlPost($url,$postFields){
$postFields = json_encode($postFields);
$ch = curl_init ();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8' //json版本需要填寫 Content-Type: application/json;
)
);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt( $ch, CURLOPT_TIMEOUT,60);
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
$ret = curl_exec ( $ch );
if (false == $ret) {
$result = curl_error( $ch);
} else {
$rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
if (200 != $rsp) {
$result = "請求狀態 ". $rsp . " " . curl_error($ch);
} else {
$result = $ret;
}
}
curl_close ( $ch );
return $result;
}