Home >Backend Development >PHP Tutorial >PHP development skills: How to implement user registration SMS verification function

PHP development skills: How to implement user registration SMS verification function

王林
王林Original
2023-09-21 14:37:48750browse

PHP development skills: How to implement user registration SMS verification function

PHP development skills: How to implement user registration SMS verification function

In the Internet era, user registration has become a common behavior for websites and applications. In order to protect users' account security and prevent malicious registration, many companies have enabled SMS verification functions. Users need to enter their mobile phone number and receive a SMS verification code when registering to confirm their identity and validity. In this article, we will introduce how to use PHP language to implement the user registration SMS verification function and provide specific code examples.

Step 1: Prepare the development environment

First, make sure you have installed the PHP parser and database, such as MySQL. In addition, you also need an available SMS platform. We will use Alibaba Cloud SMS Service (Aliyun SMS) in this example. You need to register an account with Alibaba Cloud and follow its documentation to configure and obtain an API key.

Step 2: Create database

Create a database named "users" and create a table named "users" in the database. The structure of the table is as follows:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(255) NOT NULL,
  password VARCHAR(255) NOT NULL,
  mobile VARCHAR(20) UNIQUE NOT NULL,
  status TINYINT(1) DEFAULT 0,
  verification_code VARCHAR(6) DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

In this table, we store the user's information, including user name, password, mobile phone number, user status, verification code and creation time.

Step 3: Send SMS verification code

Next, we will write a PHP function to send SMS verification code. In this function, we need to call Alibaba Cloud's SMS API and pass in the mobile phone number and verification code as parameters.

function sendSMS($mobile, $verificationCode) {
  $accessKeyId = '<Your Access Key Id>';
  $accessSecret = '<Your Access Key Secret>';
  $params = [
    'PhoneNumbers' => $mobile,
    'SignName' => '<Your Sign Name>',
    'TemplateCode' => '<Your Template Code>',
    'TemplateParam' => json_encode(['code' => $verificationCode])
  ];
  $client = new GuzzleHttpClient();
  $response = $client->request('POST', 'https://dysmsapi.aliyuncs.com/', [
    'query' => array_merge($params, ['AccessKeyId' => $accessKeyId]),
    'headers' => ['x-sdk-client' => 'php/2.0.0']
  ]);
  return $response->getBody();
}

In this function, we need to replace <your access key id></your> and <your access key secret></your> with the ones you obtained from Alibaba Cloud API key information. At the same time, you also need to replace <your sign name></your> and <your template code></your> with the SMS signature and SMS template codes you set on Alibaba Cloud.

Step 4: Process the registration request

When the user submits a registration request, we need to check whether the mobile phone number has already been registered. If not registered, we randomly generate a 6-digit verification code and save it to the database.

function registerUser($username, $password, $mobile) {
  // 检查手机号码是否已被注册
  if (checkMobileExists($mobile)) {
    return '手机号码已被注册';
  }
  // 生成随机验证码
  $verificationCode = rand(100000, 999999);
  // 保存验证码到数据库
  saveVerificationCode($mobile, $verificationCode);
  // 发送短信验证码
  $response = sendSMS($mobile, $verificationCode);
  return '短信验证码已发送';
}

function checkMobileExists($mobile) {
  // 连接数据库
  $conn = new mysqli('localhost', 'root', 'password', 'users');
  // 检查手机号码是否已存在
  $sql = "SELECT * FROM users WHERE mobile = '{$mobile}'";
  $result = $conn->query($sql);
  return $result->num_rows > 0;
}

function saveVerificationCode($mobile, $verificationCode) {
  // 连接数据库
  $conn = new mysqli('localhost', 'root', 'password', 'users');
  // 保存验证码到数据库
  $sql = "UPDATE users SET verification_code = '{$verificationCode}' WHERE mobile = '{$mobile}'";
  $conn->query($sql);
}

In this sample code, we first check whether the mobile phone number has been registered. If the mobile number already exists, we will return an error message. Otherwise, we will generate a random 6-digit verification code and save it to the database.

Step 5: Verify the verification code

When the user enters the SMS verification code received, we need to verify whether the verification code is correct. If the verification code is correct, we will update the user's status to "Verified" to indicate that the user has been verified by their mobile phone number.

function verifyCode($mobile, $verificationCode) {
  // 检查验证码是否正确
  if (checkVerificationCode($mobile, $verificationCode)) {
    // 更新用户状态
    updateStatus($mobile);
    return '手机号码验证成功';
  }
  return '验证码错误';
}

function checkVerificationCode($mobile, $verificationCode) {
  // 连接数据库
  $conn = new mysqli('localhost', 'root', 'password', 'users');
  // 检查验证码是否正确
  $sql = "SELECT * FROM users WHERE mobile = '{$mobile}' AND verification_code = '{$verificationCode}'";
  $result = $conn->query($sql);
  return $result->num_rows > 0;
}

function updateStatus($mobile) {
  // 连接数据库
  $conn = new mysqli('localhost', 'root', 'password', 'users');
  // 更新用户状态为已验证
  $sql = "UPDATE users SET status = 1 WHERE mobile = '{$mobile}'";
  $conn->query($sql);
}

In this code, we first check whether the verification code is correct. If the verification code is correct, we will update the user status to 1, indicating that the user has been verified by mobile phone number.

Summary:

Through the above steps, we successfully implemented the user registration SMS verification function. Users will receive a text message verification code when registering. By entering the correct verification code, the authenticity and validity of the mobile phone number are ensured. This SMS verification function can effectively improve the security of user accounts and prevent malicious registration and stolen accounts.

It should be noted that the above code is just a simple example. In actual projects, other security measures and verification processes may need to be improved. But through this example, you can learn how to use PHP language and Alibaba Cloud SMS service to implement the user registration SMS verification function.

Reference materials:

  • [Alibaba Cloud SMS API Document](https://help.aliyun.com/document_detail/55284.html?spm=a2c4g.11186623.6.624.649a645e4YmxKU )

The above is the detailed content of PHP development skills: How to implement user registration SMS verification function. 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