With the widespread use of smartphones, more and more websites and applications are adopting mobile verification login methods to enhance user experience and account security. This article provides a detailed explanation of how to implement mobile verification login using PHP and shares some common techniques, along with relevant code examples.
First, we need to design a user table to store account information such as mobile numbers and passwords. During login, the user will enter their phone number and password, and the backend will verify their correctness.
Here's a simple code example:
<?php // Get user input for phone number and password $phone = $_POST['phone']; $password = $_POST['password']; // Query the user table for records matching the phone number $query = "SELECT * FROM user WHERE phone = '$phone'"; $result = mysqli_query($conn, $query); // Check if a matching record is found if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); $hashed_password = $row['password']; // Verify the password if (password_verify($password, $hashed_password)) { // Successful login $_SESSION['user_id'] = $row['id']; $_SESSION['phone'] = $row['phone']; // Redirect to the user home page header('Location: home.php'); exit(); } else { // Incorrect password echo 'Invalid password'; } } else { // Phone number not found echo 'Phone number not found'; } ?>
In addition to password verification, we can also use SMS verification codes to authenticate a user's phone number. After entering the phone number, the system will send a verification code to the user's phone. The user must enter the correct code to complete the login.
Here's an example of the code:
<?php // Get user input for phone number and verification code $phone = $_POST['phone']; $code = $_POST['code']; // Check if the user-provided code matches the sent code if ($code == $_SESSION['code']) { // Verification successful $query = "SELECT * FROM user WHERE phone = '$phone'"; $result = mysqli_query($conn, $query); // Check if a matching record is found if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); // Successful login $_SESSION['user_id'] = $row['id']; $_SESSION['phone'] = $row['phone']; // Redirect to the user home page header('Location: home.php'); exit(); } else { // Phone number not found echo 'Phone number not found'; } } else { // Incorrect verification code echo 'Invalid verification code'; } ?>
This article has introduced two common methods for mobile verification login: phone number and password verification, and SMS verification code login. These methods can significantly improve the user login experience and account security. In actual development, you can combine other techniques, such as IP restrictions and device fingerprints, to implement more flexible and secure verification measures. We hope this article is helpful in improving your development process.