Home Backend Development PHP Tutorial PHP steps to implement verification code and server-side verification code

PHP steps to implement verification code and server-side verification code

Aug 04, 2018 pm 03:23 PM

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;$<4;i){

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);
?>
Copy after login

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 找了资料,没什么大用
Copy after login

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 color="#0000CC">输入正确</h1>&#39;;
    }
    else{
        header(&#39;Content-type: text/html; charset=UTF8&#39;);
        echo &#39;<h1 color="#CC0000"><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 border="1" src="captcha-2.php?r=<?php echo rand();?>" width="100" height="30">

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

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles