国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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); // 生成隨機(jī)驗(yàn)證碼

    imagefill($image, 0, 0, $bgColor);
    imagettftext($image, 20, 0, 10, 30, $textColor, $font, $code); // 在圖片上寫入驗(yàn)證碼

    // 添加干擾線
    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 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;

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="請(qǐng)輸入驗(yàn)證碼">
  <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){
    // 驗(yàn)證成功
    echo "驗(yàn)證碼輸入正確!";
} else {
    // 驗(yàn)證失敗
    echo "驗(yàn)證碼輸入錯(cuò)誤!";
}

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){ // 驗(yàn)證碼過(guò)期時(shí)間為5分鐘
        echo "驗(yàn)證碼已過(guò)期,請(qǐng)重新輸入!";
        return;
    }

    if(strtolower($inputCaptcha) === strtolower($captcha)){
        echo "驗(yàn)證碼輸入正確!";
    } else {
        echo "驗(yàn)證碼輸入錯(cuò)誤!";
    }
} else{
    echo "請(qǐng)輸入驗(yàn)證碼!";
}

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1502
276
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

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.

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

How to use Memcache for efficient data writing and querying in PHP development? How to use Memcache for efficient data writing and querying in PHP development? Nov 07, 2023 pm 01:36 PM

How to use Memcache for efficient data writing and querying in PHP development? With the continuous development of Internet applications, the requirements for system performance are getting higher and higher. In PHP development, in order to improve system performance and response speed, we often use various caching technologies. One of the commonly used caching technologies is Memcache. Memcache is a high-performance distributed memory object caching system that can be used to cache database query results, page fragments, session data, etc. By storing data in memory

How to use PHP to develop the coupon function of the ordering system? How to use PHP to develop the coupon function of the ordering system? Nov 01, 2023 pm 04:41 PM

How to use PHP to develop the coupon function of the ordering system? With the rapid development of modern society, people's life pace is getting faster and faster, and more and more people choose to eat out. The emergence of the ordering system has greatly improved the efficiency and convenience of customers' ordering. As a marketing tool to attract customers, the coupon function is also widely used in various ordering systems. So how to use PHP to develop the coupon function of the ordering system? 1. Database design First, we need to design a database to store coupon-related data. It is recommended to create two tables: one

See all articles