Home Backend Development PHP Tutorial How to develop verification code function using PHP

How to develop verification code function using PHP

Aug 17, 2023 pm 09:25 PM
php verification code development Verification code generation php PHP verification code function implementation

How to develop verification code function using PHP

How to use PHP to develop verification code function

Verification code (CAPTCHA) is a technical means used to determine whether the user is a real person or a machine. In network applications, verification codes are often used in registration, login, password reset, etc. to prevent malicious machine attacks and illegal logins. This article will introduce how to use PHP to develop verification code functions and provide corresponding code examples.

1. Generate verification code images

In PHP, we can use the GD library to generate verification code images. First, we need to create a PHP file for generating verification code images, such as captcha.php. In this file, we need to implement the following steps:

  1. Generate a random verification code string, which can be composed of numbers and letters.
<?php
session_start();
$code = '';
$length = 4;  // 验证码长度
$charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';  // 验证码字符集
$charsetLen = strlen($charset);
for ($i = 0; $i < $length; $i++) {
    $code .= $charset[mt_rand(0, $charsetLen - 1)];
}
$_SESSION['captcha_code'] = $code;  // 将验证码保存到session中
Copy after login
  1. Create a blank verification code image and set the background color and font color.
$width = 150;  // 图片宽度
$height = 50;  // 图片高度
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);  // 背景颜色为白色
$textColor = imagecolorallocate($image, 0, 0, 0);  // 字体颜色为黑色
imagefill($image, 0, 0, $bgColor);
Copy after login
  1. Draw the verification code string onto the picture.
$fontSize = 20;  // 字体大小
$fontAngle = 0;  // 字体角度
$x = 30;  // 字体X坐标
$y = 30;  // 字体Y坐标
imagettftext($image, $fontSize, $fontAngle, $x, $y, $textColor, 'path/to/font.ttf', $code);
Copy after login
  1. Add interference lines to increase the readability and security of the verification code.
$lineColor = imagecolorallocate($image, 200, 200, 200);  // 干扰线颜色为灰色
for ($i = 0; $i < 5; $i++) {
    imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $lineColor);
}
Copy after login
  1. Output the verification code image.
header('Content-type: image/png');  // 设置输出类型为PNG图片
imagepng($image);
imagedestroy($image);
Copy after login

2. Verify user input

While generating the verification code image, we also need to write code to verify whether the verification code entered by the user is correct. In operations such as login, the verification code entered by the user is usually submitted to the server through a form. We can verify whether the user input is correct by comparing it with the verification code in the session. The following is a simple example:

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $inputCode = $_POST['code'];
    $captchaCode = $_SESSION['captcha_code'];
    if (strcasecmp($inputCode, $captchaCode) === 0) {
        echo '验证通过!';
    } else {
        echo '验证码错误!';
    }
}
Copy after login

After the user submits the verification code, we can get the verification code entered by the user through $_POST['code'] and pass the strcasecmp() function (case-insensitive) Compare with the verification code in the session. If they are equal, it means that the verification code is passed.

Summary:

This article introduces how to use PHP to develop verification code functions and provides corresponding code examples. By generating verification code images and verifying the verification codes entered by users, we can enhance the security of the website and prevent malicious attacks and illegal logins. In practical applications, we can customize the style, length, character set, etc. of the verification code according to needs. At the same time, in order to improve user experience, we can also add the function of refreshing the verification code to facilitate users to obtain new verification code images.

The above is the detailed content of How to develop verification code function using PHP. 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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 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)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles