search
HomeBackend DevelopmentPHP TutorialHow to implement verification code applet in php

How to implement verification code applet in php

May 29, 2018 pm 03:35 PM
phpVerification code

This article mainly introduces the specific implementation method of the verification code applet based on PHP, and makes detailed comments, which is conducive to understanding and learning. Friends who need it can take a look together

Verification code function ( Personal understanding):

  • Reduce the pressure on the server (such as the verification code function of 12306);

  • Prevent violent registration

Personal idea: Generate n-digit random numbers from a-z, A-Z, 1-9 to form a new verification code.

Several small functions for generating verification codes

range() //Specify a range to output an array
a) For example: range(1,9)
array_merge()//Merge arrays
a) array_merge(array 1, array 2….)
array_rand (array, quantity)
a) Randomly take out several subscripts from the array and return an array

  • shuffle(array)//Will shuffle the array again Element

  • mt_rand (specify a range) //Generate a better random number

  • such as: mt_rand(1,5) // Generate an arbitrary number between 1-5

Generate verification code


<?php
 $arr1=range(&#39;a&#39;, &#39;z&#39;);//指定范围输出一个数组
 $arr2=range(&#39;A&#39;, &#39;Z&#39;);
 $arr3=range(1,9);
 $arr=array_merge($arr1,$arr2,$arr3); //合并数组
 $index = array_rand($arr,5); //在$arr中随机取5个数,返回值是$arr的下标
 Shuffle($index);
 $code = &#39;&#39;;//定义一个空的字符串来存储生成的验证码用&#39;点&#39;来进行拼接
 foreach ($index as $key => $value) {//遍历数组
 $code.= $arr[$value];//根据下标取数组中的值
 }
 var_dump($code);
?>


Screenshots of running results

Perfection: Add the verification code to the image so that the verification code is realistic

Before improving, let’s introduce the image creation The rough steps

Create an image

Method 1: Create a true color image (empty canvas)

imagecreatetruecolor(width, height) //Create a true color image

Description:

  • width: width of the canvas (pixels)

  • height: the height of the canvas (pixels)

  • The return value is the image resource

##Note:

is a true color image: fill color

imagefill(image, x, y, color) //Fill the image resource with color

Description:

  • image //Image resource

  • x, y, filled coordinate point (note: filled with the color closest to this point)

  • color; //What color to use To fill

for a true color image: Assign color

##imagecolorallocate(image, red, green, blue)

Description:

    image //Image resource
  • red: //Red color(0 -255) or 0x(00-ff) //That is, expressed in hexadecimal (0xff is 255)
  • green//Green color (0-255)
  • blue //Blue color (0-255)
  • Code demonstration of imagefill and imagecolorallocate

When the canvas is not filled with color Effect

The effect and code when filling the canvas with color

<?php
//创建图像资源(空白画布)默认显示为黑色
$image = imagecreatetruecolor(300, 400);
//1.image //图像资源
//2.red: //红颜色(0-255) 或 0x(00-ff) //即十六进制来表示 (0xff就是255)
//3.green//绿颜色(0-255)
//4.blue //蓝颜色(0-255)
$color = imagecolorallocate($image, 255, 0, 0);
//1.image //图像资源
//2.x,y,填充的坐标点(注意:填充的与此点最接近的颜色)
//3.color; //用什么颜色来填充
imagefill($image, 0, 0, $color);
//输出图像
header(&#39;content-type:image/jpeg&#39;);
imagejpeg($image);
//销毁图像资源
imagedestroy($image);
?>

## Result screenshot;

#Output image (take jpeg as an example)

Output image to browser

a ) header('content-type:image/jpeg'); //Set to view the image through browsing

b) imagejpeg (image resource)

Output the image by file

a) imagejpeg(image resource,'image path',image quality) //Quality value 0-100

b) Note:

Note: Only jpeg format has the quality parameter.

Destroy the image

imagedestroy($image); / /Destroy images and release memory resources.

Note: Destroy a few of the currently generated image resources.

Verify The entire code of the code:

<?php
//实例:让文本居于图像的正中
//创建图像资源(空白的画布)
$image = imagecreatetruecolor(100, 50);
$color = imagecolorallocate($image, mt_rand(20,200), mt_rand(20,200), mt_rand(20,200));
//为图像资源填充颜色
imagefill($image, 0, 0, $color);
//绘制图像
$font = 5;
//验证码的开始
$arr1 = range(&#39;a&#39;,&#39;z&#39;);
$arr3 = range(&#39;A&#39;,&#39;Z&#39;);
$arr2 = range(1,9);
//array_merge — 合并一个或多个数组
$arr = array_merge($arr1,$arr2,$arr3);
$index = array_rand($arr,5); //随机从原数组中找出5个下标
$string = &#39;&#39;;
foreach ($index as $value) { //$value 两个功能,即是$index中的值,又是$arr中的下标
 $string .= $arr[$value]; //将得到字符进行连接
}
//验证码的结束
//mt_rand — 生成更好的随机数
//echo mt_rand(1,5);die;
//加入点干扰
$pointcolor = imagecolorallocate($image, mt_rand(20,200), mt_rand(20,200), mt_rand(20,200));
//循环创建1000个干扰点
for ($i=0; $i <1000 ; $i++) {
 imagesetpixel($image, mt_rand(0,imagesx($image)), mt_rand(0,imagesy($image)), $pointcolor);
}
//加入线的干扰
$lintecolor = imagecolorallocate($image, mt_rand(20,200), mt_rand(20,200), mt_rand(20,200));
// 循环创建50个线干扰
for ($i=0; $i <50 ; $i++) {
 imageline($image, mt_rand(0,imagesx($image)), mt_rand(0,imagesy($image)), mt_rand(0,imagesx($image)), mt_rand(0,imagesy($image)) ,$lintecolor);
}
//一个字符的宽度 imagefontwidth($font)
//字符串的个数: strlen(字符串)    
//一个字符的宽度*字符串的个数
//所有字符串宽度和= 一个字符的宽度*字符串的个数
//$x = (画布的宽度-所有字符串宽度和)/2
$x = (imagesx($image)-imagefontwidth($font)*strlen($string))/2;
//$y = (画布的高度-字符的高度)/2;
//字符的高度: imagefontheight($font)
$y = (imagesy($image)-imagefontheight($font))/2;
$stringcolor = imagecolorallocate($image, mt_rand(20,200), mt_rand(20,200), mt_rand(20,200));
imagestring($image, $font, $x, $y, $string, $stringcolor);
//输出图像
header(&#39;content-type:image/jpeg&#39;); //设置将图像通过浏览来查看
imagejpeg($image,&#39;&#39;,100); //将图像资源输出
//销毁图像资源
imagedestroy($image); //销毁图像



Understand some functions in the code

Add interference points

imagesetpixel(image, x, y, color)

Description: x, y is a point Coordinates

Added interference line

imageline(image, x1, y1, x2, y2, color)

说明: x1,y1是线的一个端点坐标; x2,y2是线的另一个端口的坐标; 由两点画一条线

让验证码居于图像的正中


imagefontheight(font)获取字体的高度:
imagefontwidth(font)获取字体的宽度:
strlen(字符串)//获取字符串的长度
imagesx(image) //获取画布的宽度
imagesy(image) //获取画布的高度


最后运行结果

再次完善(和html代码结合起来)

Html代码


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form name=&#39;frm&#39; method=&#39;post&#39; action=&#39;&#39;>
 <table width="30%" border="2" align="center" rules="all" cellpadding="10">
 <tr>
  <th colspan="2">请输入信息</th>
 </tr>
 <tr>
  <th>姓名:</th>
  <th><input type="text" name="username"></input></th>
 </tr>
 <tr>
  <th>密码:</th>
  <th><input type="password" name="userpwd"></input></th>
 </tr>
 <tr> 555556
  <th>验证码</th>
  <th><input type = &#39;text&#39; name = &#39;checkcode&#39;></input><img  src="/static/imghwm/default1.png"  data-src="21.php"  class="lazy"     style="max-width:90%" onclick="this.src=&#39;21.php&#39;?+Math.random()" alt="How to implement verification code applet in php" ></th>
 </tr>
 <tr>
  <th colspan="2"><input type="submit" name="submit" value="提交"></input></th>
 </tr>
</table>
</form>
</body>
</html>


理解;

最后结果截图


以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

php 验证码程序

php 验证码程序_PHP教程

PHP验证码图片生成程序


The above is the detailed content of How to implement verification code applet 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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.