Home > Backend Development > PHP Problem > How to use PHP to implement user login verification code function

How to use PHP to implement user login verification code function

PHPz
Release: 2023-04-21 09:53:26
Original
2036 people have browsed it

With the development of network technology, website security issues have attracted more and more attention. As a website developer, we need to ensure the security of users' account information and personal privacy. Among them, the security of the user login process is also very important. In order to protect the security of user accounts, we need to add a verification code function to the user login page. This article will introduce how to use PHP to implement the user login verification code function.

  1. What is verification code

Verification code is a technology that distinguishes humans and computer programs, which can effectively prevent malicious attackers from using automated programs to launch attacks on websites. Common verification codes come in different forms such as numbers, letters, graphics, etc. Users need to correctly enter the verification code when logging in to verify the user's identity.

In website development, verification codes are usually embedded in the login system to prevent malicious users from obtaining system permissions through brute force cracking and other methods. At the same time, verification codes can also prevent malicious users from using automated programs to attack and brush data.

  1. Make PHP verification code

In PHP, you can use the GD extension library to draw various verification codes, including numbers, letters, graphics, etc. Below we take numerical and alphabetical verification codes as an example to introduce how to make verification codes in PHP.

2.1. Digital verification code generation

Digital verification code is the most basic form of making verification codes, and it is also the most common one. Numeric verification codes can be generated using functions in the GD library. Below is a sample code that generates a random 4-digit verification code.

<?php
session_start(); // 开启 session

header(&#39;Content-type: image/png&#39;); // 设置 Content-type

$im = imagecreatetruecolor(80, 40); // 创建一个宽为80,高为40的验证码背景图
$bgColor = imagecolorallocate($im, 255, 255, 255); // 设置背景色为白色
imagefill($im, 0, 0, $bgColor); // 绘制背景

$code = rand(1000, 9999); // 随机生成一个 4 位数的验证码
$_SESSION[&#39;code&#39;] = $code; // 把验证码存储在 Session 中,以便在其他页面中使用

$textColor = imagecolorallocate($im, 0, 0, 0); // 设置验证码颜色

imagestring($im, 5, 20, 12, $code, $textColor); // 绘制验证码

imagepng($im); // 输出 PNG 图片
imagedestroy($im); // 释放内存
?>
Copy after login

Analysis:

  • First, we enable the session function of PHP to use verification codes on other pages.
  • Then, we specify the MIME type of the verification code as image/png, telling the browser that the file is a PNG image file.
  • Next, we use the imagecreatetruecolor function to create an empty image with a width of 80 and a height of 40.
  • Then, we set a white background using the imagecolorallocate function and fill the entire image using the imagefill function.
  • Subsequently, we generate a random 4-digit verification code and store it in the session.
  • Finally, we use the imagestring function to draw the verification code in the image, and use the imagepng function to output the generated PNG image, and then destroy the image resource and release the memory.

2.2. Alphanumeric mixed verification code generation

Numeric verification codes are vulnerable to attacks, so in order to improve security, we can use a mixed alphanumeric verification code form. Likewise, we can draw the alphanumeric captcha using PHP’s GD library. Below is a sample code that generates a random 4-digit alphanumeric verification code.

<?php
session_start(); // 开启 session

header(&#39;Content-type: image/png&#39;); // 设置 Content-type

$im = imagecreatetruecolor(100, 40); // 创建一个宽为100,高为40的验证码背景图
$bgColor = imagecolorallocate($im, 255, 255, 255); // 设置背景色为白色
imagefill($im, 0, 0, $bgColor); // 绘制背景

// 字母数字集
$chars = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;
$len = strlen($chars);
$code = &#39;&#39;;
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[rand(0, $len-1)];
}

$_SESSION[&#39;code&#39;] = $code; // 把验证码存储在 Session 中,以便在其他页面中使用

$textColor = imagecolorallocate($im, 0, 0, 0); // 设置验证码颜色

// 使用随机字体和位置,绘制验证码
for ($i = 0; $i < 4; $i++) {
    $font = rand(1, 5); // 随机选择字体
    $angle = rand(-20, 20); // 随机旋转角度
    $x = $i * 20 + rand(0, 10); // 规定较小的x坐标值和x步进值,y的值也可以自定义 
    $y = rand(20, 30);
    $fontColor = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
    $char = substr($code, $i, 1);
    imagettftext($im, 18, $angle, $x, $y, $fontColor, __DIR__.&#39;/font&#39;.$font.&#39;.ttf&#39;, $char);
}

imagepng($im); // 输出 PNG 图片
imagedestroy($im); // 释放内存
?>
Copy after login

Analysis:

  • Different from the generation method of numeric verification codes, alphanumeric mixed verification codes need to first define a set of chars composed of numbers and letters, and then randomly obtain characters from it .
  • Then, we use the same method to store the verification code in the session. The drawing of
  • characters is basically the same as the digital verification code, but a ttf font file needs to be introduced to generate letters. We randomly select a font and drawing position and use the imagettftext function to draw the characters.
  1. Using the verification code on the website

After generating the verification code, you only need to introduce the program to generate the verification code in the user login page. While verifying the user's input of account and password information, it is also necessary to verify whether the verification code entered by the user is correct.

The following is a sample code for a user login page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form action="login.php" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br>

        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br>

        <label for="code">Code:</label>
        <input type="text" id="code" name="code"><br>
        <img src="captcha.php" alt="Captcha">

        <button type="submit">Submit</button>
    </form>
</body>
</html>
Copy after login

Similar to the ordinary user login page, we added a verification code part while entering the account and password, and introduced the verification code generation program captcha.php. After the user enters the account number, password and verification code, click the submit button, and the system will submit the information entered by the user to login.php for verification.

The following is the code in login.php, which is used to verify whether the account number, password and verification code information entered by the user is correct.

<?php
session_start();

$username = $_POST[&#39;username&#39;];
$password = $_POST[&#39;password&#39;];
$code = $_POST[&#39;code&#39;];

// 验证用户输入的验证码是否正确
if (strtolower($code) !== strtolower($_SESSION[&#39;code&#39;])) {
    echo &#39;Invalid Code.&#39;;
    exit;
}

// 验证用户输入的账号和密码是否正确
if ($username === &#39;admin&#39; && $password === &#39;admin&#39;) {
    echo &#39;Login Successfully.&#39;;
} else {
    echo &#39;Invalid Username or Password.&#39;;
}
?>
Copy after login

In login.php, we first verify whether the verification code entered by the user is correct. If the verification code does not match, the user is prompted to enter an invalid verification code and exit the login verification. Otherwise, we verify whether the account and password information entered by the user is correct. If it is correct, the user will be prompted to log in successfully, otherwise it will be prompted that the username or password is invalid.

  1. Summary

This article introduces how to use PHP and GD libraries to generate mixed numeric and alphanumeric verification codes, and use verification codes in websites to ensure user login Security of information. Through studying this article, you have learned how to prevent malicious users from using automated programs to attack your website, and protect the account and personal privacy of website users.

The above is the detailed content of How to use PHP to implement user login verification code function. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template