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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
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)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles