How to implement arithmetic verification code in php
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 = ['+','-','*']; //计算数组的长度 $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['res'] = $res; //输出图片 header("content-type:image/png"); imagepng($img); }/** * @param $arr 一个包含运算符号的数组 * @return 返回一个运算结果 */function getRes($arr) { $sum = 0; //判断数组元素下标为1的运算符号是什么 switch ($arr[1]){ case '+': $sum = $arr[0] + $arr[2]; break; case '-': $sum = $arr[0] - $arr[2]; break; case '*': $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="./demo5.php" 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['res'];$value = $_GET['code'];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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the popularity of Internet applications, website response speed has become more and more of a focus for users. In order to quickly respond to user requests, websites often use caching technology to cache data, thereby reducing the number of database queries. However, cache expiration time has an important impact on response speed. This article will discuss methods of controlling cache expiration time to help PHP developers better apply caching technology. 1. What is cache expiration time? Cache expiration time refers to the time when the data in the cache is considered expired. It determines when the data in the cache is needed

How to use PHP to implement file conversion and format conversion functions 1. Introduction In the process of developing web applications, we often need to implement file conversion and format conversion functions. Whether you are converting image files to other formats or converting text files from one encoding to another, these operations are common needs. This article will describe how to implement these functions using PHP, with code examples. 2. File conversion 2.1 Convert image files to other formats In PHP, we can use

How to use PHP to implement user registration function In modern network applications, user registration function is a very common requirement. Through the registration function, users can create their own accounts and use corresponding functions. This article will implement the user registration function through the PHP programming language and provide detailed code examples. First, we need to create an HTML form to receive the user's registration information. In the form, we need to include some input fields, such as username, password, email, etc. Form fields can be customized according to actual needs.

User privacy protection of online voting system implemented in PHP With the development and popularization of the Internet, more and more voting activities have begun to be moved to online platforms. The convenience of online voting systems brings many benefits to users, but it also raises concerns about user privacy leaks. Privacy protection has become an important aspect in the design of online voting systems. This article will introduce how to use PHP to write an online voting system, and focus on the issue of user privacy protection. When designing and developing an online voting system, the following principles need to be followed to ensure

Implementation Principle of Consistent Hash Algorithm for PHP Data Cache Consistent Hashing algorithm (ConsistentHashing) is an algorithm commonly used for data caching in distributed systems, which can minimize the number of data migrations when the system expands and shrinks. In PHP, implementing consistent hashing algorithms can improve the efficiency and reliability of data caching. This article will introduce the principles of consistent hashing algorithms and provide code examples. The basic principle of consistent hashing algorithm. Traditional hashing algorithm disperses data to different nodes, but when the node

How to use PHP to implement mobile adaptation and responsive design Mobile adaptation and responsive design are important practices in modern website development. They can ensure good display effects of the website on different devices. In this article, we will introduce how to use PHP to implement mobile adaptation and responsive design, with code examples. 1. Understand the concepts of mobile adaptation and responsive design Mobile adaptation refers to providing different styles and layouts for different devices based on the different characteristics and sizes of the device. Responsive design refers to the use of

With the continuous development of WeChat mini programs, more and more users are beginning to choose WeChat mini programs to log in. In order to improve users’ login experience, WeChat mini programs began to support fingerprint login. In this article, we will introduce how to use PHP to implement fingerprint login for WeChat mini programs. 1. Understand the fingerprint login of WeChat mini programs On the basis of WeChat mini programs, developers can use WeChat's fingerprint recognition function to allow users to log in to WeChat mini programs through fingerprints, thereby improving the security and convenience of the login experience. 2. Preparation work is implemented using PHP

With the rapid development of the mobile Internet, WeChat mini programs are becoming more and more popular among users, and PHP, as a powerful programming language, also plays an important role in the development process of mini programs. This article will introduce the techniques of implementing WeChat applet operation flow chart in PHP. Obtain access_token During the development process of using WeChat applet, you first need to obtain access_token, which is an important credential for realizing the operation of WeChat applet. The code to obtain access_token in PHP is as follows: f
