search
HomeBackend DevelopmentPHP TutorialPHP steps to implement verification code and server-side verification code

This article introduces to you the steps to implement verification code in PHP and the server-side verification code. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is the verification code: The verification code is a public program that distinguishes whether the user is a computer or a human.

It takes four steps to make a verification code

1: Generate a base map

2: Generate verification content

3: Generate verification code content

4: Verify verification content

First step by step, the first step, Generate base map:

Goal: Generate a 100*30 size image through php

Method: imagecreatetruecolor($width,$height);

Note Matters: Relying on GD extension

Before outputting a picture, the header information of that picture must be output in advance--》》Send native http header

This method outputs a black background by default

imagecreatetruecolor() Create a new true color image represented by $image. Later, it will be used a lot.

Since we are creating a true color image, we must have a variety of colors. Next, imagecolorallocate(select canvas, three colors Parameters)

What do you want to use to fill imagefill (select canvas, starting position, color)

With this, the base image is generated, let’s start adding some ingredients

$image = imagecreatetruecolor(100,30)

$bgcolor = imagecolorallocate($image,255,255,255);

imagefill($image,0,0,$bgcolor)

Step 2: Generate verification content

Goal: Randomly generate numbers (size, starting position, content, color)

Method: Generate a line of characters horizontally through loops and imagestring functions String (fill in according to the parameter position in imagestring)

Note: Control the font size, N/n

for($i=0;$

Here, define variables based on the parameters in imagestring, and assign values ​​to variables

imagestring($image,$fontsze,$x,$y,$fontcontent,$fontcolor)

}

$fontcontent = substr($data,rand(0,strlen($data)),1);

If you want numbers and letters Combination, the substr method means to return the substring of the string. The returned string randomly obtains data. From here on, it has a length of up to 1

The third step is to generate the verification code content

Goal: Add interference elements to the verification code, interference elements are points or lines

Method: imagesetpixel point, imageline-line (resource file, starting position, color)

Notes: Interference elements Be sure to control the color and quantity to avoid overestimating the guest.

Step 4: Store the verification information through the session

Goal: Record on the server side to facilitate verification after the user enters the verification code

Method: session_start()

Note: session_start() must be at the top of the script

In the case of multiple services, centralized management of session management should be considered

imagepng Output the image to the browser or file in png format

imagedestroy Good habit of destroying the image

In these methods, a lot of resources are used, that is, each method requires the $image canvas

<php?
$image = imagecreatetruecolor( 100,30);
$bgcolor = imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);
// for($i=0;$i<4;$i++){
// $fontsize = 6;
// $fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
// $fontcontent = rand(0,9);
// $x = ($i*100/4)+rand(5,10);
// $y = rand(5,10);
// imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor );
// }
$captch_code= &#39;&#39;;
for($i=0 ;$i<4;$i++){
    $fontsize = 6;
    $fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
    $data = &#39;abcdefhijkimnpqrstuvwxy345678&#39;;
    $fontcontent = substr($data,rand(0,strlen($data)),1); 
    $captch_code.=$fontcontent;
    $x = ($i*100/4)+rand(5,10);
    $y = rand(5,10);
    imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor );
    
}
$SESSION[&#39;authcode&#39;]=$captch_code;
for($i=0;$i<200;$i++){
$pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($image,rand(1,99),rand(1,99),$pointcolor);
}
for($i=0;$i<3;$i++){
$linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));
imageline($image,rand(1,99),rand(1,99),rand(1,99),rand(1,99),$pointcolor);
}
header(&#39;content-type: image/png&#39;);
imagepng( $image);
//end;
imagedestroy( $iamge);
?>

The production of verification code ends here. The next step is to perform verification on the server side

src="captcha-2.php?r=<?php  echo rand();?>"   对于这个r 找了资料,没什么大用

This is the original intention

He also uses t here, so r ah t ah

Taking into account the case, strtolower() is used here to convert all uppercase letters entered by the user into lowercase letters

<?php

if(isset($_REQUEST[&#39;code&#39;]))
{
    session_start();
    if (strtolower($_REQUEST[&#39;code&#39;])==$_SESSION[&#39;code&#39;])
    {
        header(&#39;Content-type: text/html; charset=UTF8&#39;);
        echo &#39;<h1 id="输入正确">输入正确</h1>&#39;;
    }
    else{
        header(&#39;Content-type: text/html; charset=UTF8&#39;);
        echo &#39;<h1 id="b-输入错误-b"><b>输入错误</b></h1>&#39;;
    }
    exit();
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>确认验证</title>
</head>
<body>
<form method="post" action="form.php">
    <p>验证码图片:<img  src="/static/imghwm/default1.png"  data-src="captcha-2.php?r=<?php echo rand();? alt="PHP steps to implement verification code and server-side verification code" >"  class="lazy"  border="1"  width="100"    style="max-width:90%">

    </p>
    <p>请输入图片的内容:<input type="text" name="code" value=""/></p>
    <p><input type="submit" value="提交" style="padding:6px 20px;"></p>
</form>
</body>
</html>

Recommended related articles:

How to use PHP Convert the txt file content into an array and get the specified content by line number (example)

How does php use longitude and latitude to calculate the distance between two points (pure code)

php code example of how to delete a directory and all files in the directory

The above is the detailed content of PHP steps to implement verification code and server-side verification code. 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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use