search
HomeBackend DevelopmentPHP TutorialHow to generate refreshable image verification code using PHP

How to generate refreshable image verification code using PHP

How to use PHP to generate a refreshable image verification code

With the development of the Internet, in order to prevent malicious attacks and automatic machine operations, many websites use verification code for user authentication. One common type of verification code is the image verification code, which generates a picture containing random characters and requires the user to enter the correct characters before proceeding.

This article will introduce how to use PHP to generate refreshable image verification codes and provide specific code examples.

Step 1: Create a verification code image

First, we need to create a function for generating a verification code image. Through PHP's GD library, we can easily manipulate images. The following is a sample code for creating a verification code image:

<?php
function generateCaptcha($length = 6) {
    // 生成随机的验证码字符串
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $captcha = '';
    for ($i = 0; $i < $length; $i++) {
        $captcha .= $chars[rand(0, strlen($chars) - 1)];
    }

    // 将验证码字符串保存到Session中,以备后续验证
    session_start();
    $_SESSION['captcha'] = $captcha;

    // 创建一个空白的验证码图片
    $image = imagecreatetruecolor(120, 40);
    $background_color = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $background_color);

    // 在验证码图片上绘制随机的字符
    $text_color = imagecolorallocate($image, 0, 0, 0);
    imagettftext($image, 20, 0, 10, 30, $text_color, 'path/to/font.ttf', $captcha);

    // 输出验证码图片
    header('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);
}
?>

In the above code, the generateCaptcha function is used to generate a verification code and save the verification code string to the Session. Then, create a blank verification code picture, set the background color, text color, font and other parameters, and draw the verification code on the picture. Finally, set the output content type to image through the header function, call the imagepng function to output the image, and then destroy the image resource.

Step 2: Use the verification code image

The following is a simple sample code for displaying the verification code image on the web page and accepting the verification code entered by the user:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>生成验证码</title>
</head>
<body>
    <form action="verify_captcha.php" method="post">
        <label for="captcha">请输入验证码:</label>
        <input type="text" id="captcha" name="captcha">
        <img src="/static/imghwm/default1.png"  data-src="captcha.php"  class="lazy" alt="验证码">
        <button type="submit">提交</button>
    </form>
</body>
</html>

In the above code, the action attribute of the form form points to a PHP file that verifies the verification code (such as verify_captcha.php), img## The src attribute of the #tag points to the PHP file that generates the verification code image (such as captcha.php). After the user enters the verification code in the input box, the form is submitted and verified.

Step 3: Verify the entered verification code

Finally, we need to create a PHP file to verify whether the verification code entered by the user is correct. The following is a simple sample code for verifying the verification code:

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $inputCaptcha = $_POST['captcha'];
    $captcha = $_SESSION['captcha'];

    if ($inputCaptcha === $captcha) {
        echo '验证码正确';
    } else {
        echo '验证码错误';
    }
}
?>

In the above code, the Session is first opened through the

session_start function, and then the verification code entered by the user and previously saved in the Session are obtained Verification codes are compared. If they are the same, output "verification code is correct"; if they are different, output "verification code is wrong".

The above are the steps and code examples for using PHP to generate refreshable image verification codes. In this way, we prevent automated machines from operating and increase the security of our websites and applications.

The above is the detailed content of How to generate refreshable image verification code using PHP. 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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software