search
HomeBackend DevelopmentPHP TutorialHow to implement arithmetic verification code in php

How to implement arithmetic verification code in php

Jul 05, 2018 pm 03:04 PM
php implementation

This article mainly introduces the method of implementing arithmetic verification code in PHP. It has certain reference value. Now I share it with you. Friends in need can refer to it.

I have recently learned PHP. I also practiced the implementation of image functions and verification codes. Following the teacher’s advice, I wrote an arithmetic verification code function. It was the first time I completed a small exercise independently. I felt quite happy. However, I also knew my own limitations. , so I wrote it out specifically, hoping that the experts from all walks of life can give me some guidance and expand my horizons more

The php code is as follows: Implement the function of the verification code

<?php/**
 * @param int $width 宽度,默认为120
 * @param int $height 高度,默认为50
 * @param int $fontSize 字体的大小
 * @return 图片资源
 */function arithmeticCode($width=120,$height=50,$fontSize=20){
    //开启session
    session_start();    //创建画布
    $img = imagecreatetruecolor($width,$height);    //分配颜色
    $color = imagecolorallocate($img,255,255,255);    //填充颜色
    imagefill($img,0,0,$color);    //干扰点
    for ($i = 0;$i < 500;$i++){        $pixColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
        imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pixColor);
    }    //干扰线
    for ($i = 0;$i < 4;$i++){        $lineColor = imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
        imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$lineColor);
    }    //定义一个数组存放运算符号
    $arr = [&#39;+&#39;,&#39;-&#39;,&#39;*&#39;];    //计算数组的长度
    $len = count($arr);    //定义一个1到20的数组
    $num = range(1,20);    $numLen = count($num);    //定义一个空数组来存放随机取得的验证码
    $code = [];    for ($i = 0;$i < $len;$i++) {        if ($i == 1) {            $code[] = $arr[mt_rand(0,$len-1)];
        }else {            $code[] = $num[mt_rand(0,$numLen-1)];
        }
    }    $str = implode($code);//将数组转为字符串
    $textColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));    $fontAngle = 0;    $x = ($width - $fontSize*3)/2;    $y = ($height - $fontSize) / 2 + $fontSize;
    imagettftext($img,$fontSize,$fontAngle,$x,$y,$textColor,"./img/msyh.ttc",$str);    $res = getRes($code);    //将函数存放在session中
    $_SESSION[&#39;res&#39;] = $res;    //输出图片
    header("content-type:image/png");
    imagepng($img);
}/**
 * @param $arr 一个包含运算符号的数组
 * @return 返回一个运算结果
 */function getRes($arr) {
    $sum = 0;    //判断数组元素下标为1的运算符号是什么
    switch ($arr[1]){        case &#39;+&#39;:            $sum = $arr[0] + $arr[2];            break;        case &#39;-&#39;:            $sum = $arr[0] - $arr[2];            break;        case &#39;*&#39;:            $sum = $arr[0] * $arr[2];            break;
    }    return $sum;
}//调用函数arithmeticCode(100,40,18);

Part of the code of html

<!doctype html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {            position: relative;            top: 20px;        }
    </style></head><body><form action="test.php">
    验证码 <input type="text" name="code">
    <img src="/static/imghwm/default1.png"  data-src="./demo5.php"  class="lazy"   alt="点击刷新">
    <br>
    <button>提交</button></form></body></html><script>
    //实现点击图片刷新验证码的功能
    var img = document.querySelector("img");
    img.onclick = function () {
        this.src = this.src+"?m="+Math.random();
    }</script>

Test of test.php

<?phpsession_start();$res = $_SESSION[&#39;res&#39;];$value = $_GET[&#39;code&#39;];if ($res == $value) {    echo "test success";
}else{    echo "test fail";
}

The above is the composition of my code.
I hope everyone can The great god is willing to teach you [Looking forward to the face]

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Introduction to the use of MongoDB Driver in PHP7

Assigning values ​​in an array to a set of variables in PHP method

The above is the detailed content of How to implement arithmetic verification code in 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.

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

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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