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

PHP development: How to implement the image verification code function

Sep 20, 2023 pm 04:00 PM
php development Implement function Image verification code

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;
}
Copy after login

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 src="/static/imghw/default1.png" data-src="captcha.php" class="lazy" 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;
Copy after login

Create a verification code input box and submit button:

<form action="verify.php" method="POST">
  <img src="/static/imghw/default1.png"  data-src="captcha.php"  class="lazy" alt="captcha image">
  <input type="text" name="captcha" placeholder="请输入验证码">
  <button type="submit">提交</button>
</form>
Copy after login

Verify the verification code entered by the user:

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

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

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 "请输入验证码!";
}
Copy after login

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

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

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if Google Chrome does not display the verification code image? Chrome browser does not display the verification code? What should I do if Google Chrome does not display the verification code image? Chrome browser does not display the verification code? Mar 13, 2024 pm 08:55 PM

What should I do if Google Chrome does not display the verification code image? Sometimes you need a verification code to log in to a web page using Google Chrome. Some users find that Google Chrome cannot display the content of the image properly when using image verification codes. What should be done? The editor below will introduce how to deal with the Google Chrome verification code not being displayed. I hope it will be helpful to everyone! Method introduction: 1. Enter the software, click the "More" button in the upper right corner, and select "Settings" in the option list below to enter. 2. After entering the new interface, click the "Privacy Settings and Security" option on the left. 3. Then click "Website Settings" on the right

How to use Laravel to implement image processing functions How to use Laravel to implement image processing functions Nov 04, 2023 pm 12:46 PM

How to use Laravel to implement image processing functions requires specific code examples. Nowadays, with the development of the Internet, image processing has become an indispensable part of website development. Laravel is a popular PHP framework that provides us with many convenient tools to process images. This article will introduce how to use Laravel to implement image processing functions, and give specific code examples. Install LaravelInterventionImageInterven

How to use Memcache in PHP development? How to use Memcache in PHP development? Nov 07, 2023 pm 12:49 PM

In web development, we often need to use caching technology to improve website performance and response speed. Memcache is a popular caching technology that can cache any data type and supports high concurrency and high availability. This article will introduce how to use Memcache in PHP development and provide specific code examples. 1. Install Memcache To use Memcache, we first need to install the Memcache extension on the server. In CentOS operating system, you can use the following command

Use uniapp to implement image rotation function Use uniapp to implement image rotation function Nov 21, 2023 am 11:58 AM

Using uniapp to implement image rotation function In mobile application development, we often encounter scenarios where images need to be rotated. For example, the angle needs to be adjusted after taking a photo, or an effect similar to the rotation of a camera after taking a photo is achieved. This article will introduce how to use the uniapp framework to implement the image rotation function and provide specific code examples. uniapp is a cross-platform development framework based on Vue.js, which can simultaneously develop and publish applications for iOS, Android, H5 and other platforms. Implemented in uniapp

How to register for the Hotcoin Global exchange? How to download the Hotcoin Global App? Hotcoin Global official website registration tutorial How to register for the Hotcoin Global exchange? How to download the Hotcoin Global App? Hotcoin Global official website registration tutorial Aug 16, 2024 pm 05:18 PM

How to register for HotcoinGlobal Exchange: Visit the official website: https://www.hotcoin.global/ Select the registration method: Email or mobile phone number Fill in the registration information (email or mobile phone number, password, verification code) Agree to the user agreement and obtain Verification code Enter the verification code to complete registration

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Node.js development: How to implement user rights management functions Node.js development: How to implement user rights management functions Nov 08, 2023 am 09:17 AM

Title: Node.js Development: User Rights Management Function Implementation and Code Examples Abstract: As the complexity of web applications and systems continues to increase, user rights management has become an important function that cannot be ignored. This article will introduce how to implement user rights management functions in Node.js development and give specific code examples. Introduction: As an efficient and lightweight development platform, Node.js has a wide range of application scenarios. In the development of many Node.js applications, user rights management is often an essential function.

How to implement version control and code collaboration in PHP development? How to implement version control and code collaboration in PHP development? Nov 02, 2023 pm 01:35 PM

How to implement version control and code collaboration in PHP development? With the rapid development of the Internet and the software industry, version control and code collaboration in software development have become increasingly important. Whether you are an independent developer or a team developing, you need an effective version control system to manage code changes and collaborate. In PHP development, there are several commonly used version control systems to choose from, such as Git and SVN. This article will introduce how to use these tools for version control and code collaboration in PHP development. The first step is to choose the one that suits you

See all articles