Home  >  Article  >  Backend Development  >  PHP development: How to implement the image verification code function

PHP development: How to implement the image verification code function

PHPz
PHPzOriginal
2023-09-20 16:00:361114browse

PHP development: How to implement the image verification code function

PHP development: How to implement the image verification code function

In WEB development, in order to prevent robots or malicious attacks, it is often necessary to use verification codes to verify the user's identity. Among them, picture verification code is a common type of verification code, which can not only effectively identify users, but also improve user experience. This article will introduce how to use PHP to implement the image verification code function and provide specific code examples.

1. Generate a verification code image

First, we need to generate a verification code image with random characters. PHP provides the GD library to easily generate images. The following is an example of a function that generates a verification code image:

function generateCaptchaImage($length = 4, $width = 120, $height = 40, $font = 'path/to/font.ttf'){
    $image = imagecreatetruecolor($width, $height);
    $bgColor = imagecolorallocate($image, 255, 255, 255);
    $textColor = imagecolorallocate($image, 0, 0, 0);
    $code = generateRandomCode($length); // 生成随机验证码

    imagefill($image, 0, 0, $bgColor);
    imagettftext($image, 20, 0, 10, 30, $textColor, $font, $code); // 在图片上写入验证码

    // 添加干扰线
    for ($i = 0; $i < 5; $i++) {
        $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
        imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
    }

    // 输出图像
    header('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);
    
    return $code;
}

function generateRandomCode($length = 4){
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    $code = '';
    
    for ($i = 0; $i < $length; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    
    return $code;
}

The above function generateCaptchaImage is used to generate a verification code image and returns the verification code string as the function return value.

2. Display the verification code image and verify user input

In the page where the verification code is to be displayed, you can display the verification code image through the <img alt="PHP development: How to implement the image verification code function" > tag. And use session to save the verification code.

session_start();
$captcha = generateCaptchaImage();
$_SESSION['captcha'] = $captcha;

Create a verification code input box and submit button:

<form action="verify.php" method="POST">
  <img src="captcha.php" alt="captcha image">
  <input type="text" name="captcha" placeholder="请输入验证码">
  <button type="submit">提交</button>
</form>

Verify the verification code entered by the user:

session_start();
$captcha = $_SESSION['captcha'];

if(isset($_POST['captcha']) && $_POST['captcha'] == $captcha){
    // 验证成功
    echo "验证码输入正确!";
} else {
    // 验证失败
    echo "验证码输入错误!";
}

3. Verification code verification and expiration processing

In order to enhance the security of the verification code, we can also add expiration time and verification code processing. The following is an enhanced version of the verification code verification example:

session_start();
if(isset($_POST['captcha']) && isset($_SESSION['captcha'])){
    $captcha = $_SESSION['captcha'];
    $inputCaptcha = $_POST['captcha'];
    
    if(time() - $_SESSION['captcha_time'] > 300){ // 验证码过期时间为5分钟
        echo "验证码已过期,请重新输入!";
        return;
    }

    if(strtolower($inputCaptcha) === strtolower($captcha)){
        echo "验证码输入正确!";
    } else {
        echo "验证码输入错误!";
    }
} else{
    echo "请输入验证码!";
}

When generating the verification code, the current time is also saved in $_SESSION:

session_start();
$captcha = generateCaptchaImage();
$_SESSION['captcha'] = $captcha;
$_SESSION['captcha_time'] = time();

The above code will After verifying the expiration time and verifying the verification code, the corresponding prompt information is output.

Summary:

Through the above steps, we can use PHP to implement the image verification code function. First, a verification code image with random characters is generated and displayed on the page. Then, the verification code entered by the user is compared with the verification code saved on the server to determine whether the input is correct. At the same time, in order to increase the security of the verification code, you can set the expiration time and add verification code processing. The implementation of the verification code function can be used in sensitive operations such as user registration and login to improve system security and user experience.

Note: In order for the above code to run normally, you need to ensure that the GD library has been installed correctly.

The above is the detailed content of PHP development: How to implement the image verification code 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