Home  >  Article  >  Backend Development  >  How to send mobile phone verification code and SMS notification when user logs in in PHP

How to send mobile phone verification code and SMS notification when user logs in in PHP

王林
王林Original
2023-09-25 10:07:431216browse

How to send mobile phone verification code and SMS notification when user logs in in PHP

How to send mobile phone verification codes and SMS notifications when users log in in PHP

With the popularity of smart phones, mobile phones have become indispensable in our lives One of the tools. In websites or applications, providing users with mobile phone verification codes and SMS notification functions can not only improve user security, but also increase user experience. This article will introduce how to implement the function of sending mobile phone verification codes and SMS notifications when users log in in PHP, and provide specific code examples.

  1. Generation and sending of mobile phone verification code
    In the user login page, we usually provide an input box for entering the mobile phone number. After the user enters the mobile phone number and clicks the Send Verification Code button, the system will generate a verification code and send the verification code to the mobile phone number entered by the user.

First, we need to use a third-party SMS interface provider. In this example, we choose to use the SMS service provided by Alibaba Cloud.

After registering an account on Alibaba Cloud SMS Service and activating the SMS service, we can obtain an access key for permission authentication in the code. For specific activation steps, please refer to Alibaba Cloud's help documentation.

Next, we can write a send_sms_code.php file to handle the logic of sending verification codes.

<?php
require_once 'aliyun-php-sdk-core/Config.php'; // 引入阿里云SDK库

$accessKeyId = 'your_access_key_id'; // 替换成你的AccessKeyId
$accessKeySecret = 'your_access_key_secret'; // 替换成你的AccessKeySecret
$signName = 'your_sign_name'; // 替换成你的短信签名名称
$templateCode = 'your_template_code'; // 替换成你的短信模板CODE

// 生成一个6位随机数字验证码
$code = rand(100000, 999999);

// 将手机号码和验证码存储到Session中,用于后续验证
$_SESSION['sms_code'] = $code;
$_SESSION['phone_number'] = $_POST['phone_number'];

// 发送短信验证码
$data = array(
    'PhoneNumbers' => $_POST['phone_number'],
    'SignName' => $signName,
    'TemplateCode' => $templateCode,
    'TemplateParam' => json_encode(array('code' => $code)), // 模板参数
);

// 使用阿里云SDK发送短信
$profile = DefaultProfile::getProfile('cn-hangzhou', $accessKeyId, $accessKeySecret);
$client = new DefaultAcsClient($profile);
$request = new DysmsapiRequestV20170525SendSmsRequest();
$request->setPhoneNumbers($data['PhoneNumbers']);
$request->setSignName($data['SignName']);
$request->setTemplateCode($data['TemplateCode']);
$request->setTemplateParam($data['TemplateParam']);
$response = $client->getAcsResponse($request);

// 返回发送结果(示例中只简单返回成功或失败)
if ($response->Code == 'OK') {
    echo json_encode(array('status' => 'success', 'message' => '验证码发送成功'));
} else {
    echo json_encode(array('status' => 'error', 'message' => $response->Message));
}
?>

In the above code, we first obtain the mobile phone number entered by the user and the generated verification code, and store them in the Session. Then, we use the SDK of Alibaba Cloud SMS Service to send text messages. Among them, $accessKeyId, $accessKeySecret, $signName, and $templateCode are the credentials and template information of the Alibaba Cloud SMS service mentioned above respectively.

The returned sending result is output in JSON format for processing by the front-end page.

  1. Verification code verification when user logs in
    After the user enters the mobile phone number and verification code, click the login button, we need to verify whether the verification code entered by the user matches the verification code sent previously, so as to Ensure the legitimacy of user identity.

We can write a check_sms_code.php file to handle the logic of verification code verification.

<?php
session_start();

$enteredCode = $_POST['code']; // 用户输入的验证码
$storedCode = $_SESSION['sms_code']; // 存储在Session中的验证码

if ($enteredCode == $storedCode) {
    // 验证码验证通过,执行用户登录逻辑
    // TODO: 执行用户登录逻辑
    echo json_encode(array('status' => 'success', 'message' => '验证码验证通过'));
} else {
    // 验证码验证失败
    echo json_encode(array('status' => 'error', 'message' => '验证码验证失败'));
}
?>

In the above code, we obtain the stored verification code from the Session, and then compare it with the verification code entered by the user. If they match, the verification code is deemed to have passed the verification and the corresponding user login logic can be executed. Otherwise, the verification code verification is considered failed.

Through the above code examples, we can easily implement the function of sending mobile phone verification codes and SMS notifications when users log in in PHP. Of course, there may be more complex logic in actual applications, but the basic principles and methods are the same. Hope this article helps you!

The above is the detailed content of How to send mobile phone verification code and SMS notification when user logs in in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn