本文操作环境:windows10系统、PHP 7、thindpad t480电脑。我们在使用手机号注册时通常需要发送短信验证码,在进行修改密码等敏感操作时也需要手机号发送短信验证码。那么在实际项目中如果要发送短信验证码该如何做呢?通常是需要
本文操作环境:windows10系统、PHP 7、thindpad t480电脑。
我们在使用手机号注册时通常需要发送短信验证码,在进行修改密码等敏感操作时也需要手机号发送短信验证码。那么在实际项目中如果要发送短信验证码该如何做呢?通常是需要调用第三方短信商的短信发送接口。
下面就让我们一起来看看如何实现吧!
手机注册:
可以将接口地址和appkey放在配置文件中。封装一个函数sendmsg用于发送短信,可以用php中的curl请求方式(PHP中的curl函数库)发送请求。
if (!function_exists('sendmsg')) {
function sendmsg($phone, $msg){
//从配置文件读取接口信息
$gateway = config('msg.gateway');
$appkey = config('msg.appkey');
//准备请求地址
$url = $gateway . "?appkey=" . $appkey . "&mobile=" . $phone . "&content=" . $msg;
//发送请求 比如get方式 https请求
$res = curl_request($url, false, [], true);
if (!$res) {
return "请求发送失败";
}
//请求发送成功,返回值JSON格式字符串
$arr = json_decode($res, true);
if ($arr['code'] == 10000) {
return true;
}
return $arr['msg'];
}
}
在控制器里定义一个sendcode方法,当前台点击发送验证码发送ajax请求,该方法接收到前台注册用户的手机号,调用sendmsg函数实现验证码短信发送功能。
//ajax请求发送注册验证码
public function sendcode($phone)
{
//参数验证
if (empty($phone)) {
return ['code' => 10002, 'msg' => '参数错误'];
}
//短信内容 您用于注册的验证码为:****,如非本人操作,请忽略。
$code = mt_rand(1000, 9999);
$msg = "您用于注册的验证码为:{$code},如非本人操作,请忽略。";
//发送短信
$res = sendmsg($phone, $msg);
if ($res === true) {
//发送成功,存储验证码到session 用于后续验证码的校验
session('reGISter_code_' . $phone, $code);
return ['code' => 10000, 'msg' => '发送成功', 'data' => $code];
}
return ['code' => 10001, 'msg' => $res];
}
邮箱注册:
PHP中邮箱注册可以使用PHPMailer插件来实现邮件发送(具体可查看PHPMailer手册)。在配置文件中配置好邮箱账号信息,封装一个send_email函数使用phpmailer发送邮件。
if (!function_exists('send_email')) {
//使用PHPMailer发送邮件
function send_email($email, $subject, $body){
//实例化PHPMailer类 不传参数(如果传true,表示发生错误时抛异常)
$mail = new PHPMailer();
// $mail->SMTPDebug = 2; //调试时,开启过程中的输出
$mail->iSSMTP(); // 设置使用SMTP服务
$mail->Host = config('email.host'); // 设置邮件服务器的地址
$mail->SMTPAuth = true; // 开启SMTP认证
$mail->Username = config('email.email'); // 设置邮箱账号
$mail->PassWord = config('email.password'); // 设置密码(授权码)
$mail->SMTPSecure = 'tls'; //设置加密方式 tls ssl
$mail->Port = 25; // 邮件发送端口
$mail->CharSet = 'utf-8'; //设置字符编码
//Recipients
$mail->setFrom(config('email.email'));//发件人
$mail->addAddress($email); // 收件人
//Content
$mail->ishtml(true); // 设置邮件内容为html格式
$mail->Subject = $subject; //主题
$mail->Body = $body;//邮件正文
// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if ($mail->send()) {
return true;
}
return $mail->ErrorInfo;
// $mail->ErrorInfo
}
}
然后在控制器的方法中调用该函数,实现本邮箱向注册用户邮箱发送验证邮件功能。
--结束END--
本文标题: php如何实现手机注册
本文链接: https://www.lsjlt.com/news/290.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0