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

PHP development skills: How to implement the verification code function

Sep 21, 2023 pm 01:16 PM
Verification code php development Skill

PHP development skills: How to implement the verification code function

PHP development skills: How to implement the verification code function

Verification code (CAPTCHA) is a common technology used to verify user identity and is used in website development. widely used. Verification codes can effectively prevent malicious registration by robots, brute force cracking and other malicious behaviors, and improve the security of the website. This article will introduce how to use PHP language to implement the verification code function and provide specific code examples.

1. Generate verification code

Generating verification code is the first step to realize the verification code function. We can create pictures through the GD library and draw randomly generated verification code characters on the pictures. The following is a sample code for generating a verification code:

<?php
session_start();

// 随机生成验证码字符
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$randomString = '';
$length = 6;

for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
}

// 将验证码字符保存到session中
$_SESSION['captcha'] = $randomString;

// 创建验证码图片
$image = imagecreatetruecolor(200, 100);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);

imagefilledrectangle($image, 0, 0, 200, 100, $bgColor);
imagettftext($image, 40, 0, 60, 60, $textColor, 'font.ttf', $randomString);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
Copy after login

In the above code, first we use the session_start() function to open the session to store the verification code characters. We then randomly select characters through the loop, save them into the variable $randomString, and store them in $_SESSION['captcha']. Next, use the imagecreatetruecolor() function to create a canvas $image with a size of 200x100 pixels, and set the background color and text color. Use the imagefilledrectangle() function to fill the canvas with white, and then use the imagettftext() function to draw the captcha characters on the canvas. Finally, use the header() function to set the response type to image/png, and use the imagepng() function to output the canvas as a PNG image.

2. Verification code verification

After generating the verification code, we need to display it on the web page and provide an input box for the user to enter the verification code. When the user submits the form, we need to verify the correctness of the verification code. The following is a sample code for verification code verification:

<?php
session_start();

// 获取用户输入的验证码
$userCaptcha = $_POST['captcha'];

// 验证码比较(不区分大小写)
if (strcasecmp($userCaptcha, $_SESSION['captcha']) == 0) {
    echo '验证码正确';
} else {
    echo '验证码错误';
}

// 清除session中的验证码
unset($_SESSION['captcha']);
?>
Copy after login

In the above code, first we use the session_start() function to open the session, and then obtain the verification code entered by the user from the form submitted by the user $_POST['captcha' ]. Then, use the strcasecmp() function to compare the verification code entered by the user with the verification code stored in the session. The strcasecmp() function is a case-insensitive string comparison function that returns 0 to indicate equality and non-zero to indicate inequality. Output corresponding information based on the comparison results. Finally, use the unset() function to clear the verification code in the session for next time use.

3. Use the verification code function

The following is a sample code for using the verification code function:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>验证码示例</title>
</head>
<body>
    <form action="verify.php" method="POST">
        <img src="/static/imghw/default1.png"  data-src="captcha.php"  class="lazy" alt="验证码">
        <input type="text" name="captcha" placeholder="请输入验证码">
        <input type="submit" value="提交">
    </form>
</body>
</html>
Copy after login

In the above code, we used PHP development skills: How to implement the verification code function

Summary

This article introduces how to use PHP language to implement the verification code function and provides specific code examples. By generating random characters and drawing verification code images, we can effectively prevent attacks by bots and malicious actors on the website. When using the verification code function, you need to pay attention to protecting the security of the verification code characters to prevent them from being guessed by malicious programs. I hope this article can help you understand and apply the verification code function.

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

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)

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

Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Mar 27, 2024 pm 02:57 PM

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

What are the tips for novices to create forms? What are the tips for novices to create forms? Mar 21, 2024 am 09:11 AM

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! Mar 26, 2024 am 08:21 AM

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

PHP programming skills: How to jump to the web page within 3 seconds PHP programming skills: How to jump to the web page within 3 seconds Mar 24, 2024 am 09:18 AM

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Win11 Tricks Revealed: How to Bypass Microsoft Account Login Win11 Tricks Revealed: How to Bypass Microsoft Account Login Mar 27, 2024 pm 07:57 PM

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

Tips for using Laravel form classes: ways to improve efficiency Tips for using Laravel form classes: ways to improve efficiency Mar 11, 2024 pm 12:51 PM

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel

See all articles