Home Backend Development PHP Tutorial An explanation of the php Captcha verification code class

An explanation of the php Captcha verification code class

Jun 11, 2018 pm 04:44 PM
function session

<?php
/** Captcha 驗證碼類
*	Date: 	2011-02-19
*	Author:	fdipzone
*/
class Captcha{	//class start
	private $sname = &#39;&#39;;
	public function __construct($sname=&#39;&#39;){	// $sname captcha session name
		$this->sname = $sname==''? 'm_captcha' : $sname;
	}
	/** 生成验证码图片
	* @param  int	$length 驗證碼長度
	* @param  Array	$param  參數
	* @return IMG
	*/
	public function create($length=4,$param=array()){
		Header("Content-type: image/PNG");
		$authnum = $this->random($length);	//生成验证码字符.
	
		$width	= isset($param['width'])? $param['width'] : 13;		//文字宽度
		$height = isset($param['height'])? $param['height'] : 18;	//文字高度
		$pnum	= isset($param['pnum'])? $param['pnum'] : 100;		//干扰象素个数
		$lnum	= isset($param['lnum'])? $param['lnum'] : 2;		//干扰线条数
		$this->captcha_session($this->sname,$authnum);				//將隨機數寫入session
		$pw = $width*$length+10;
		$ph = $height+6;
				
		$im = imagecreate($pw,$ph);						//imagecreate() 新建图像,大小为 x_size 和 y_size 的空白图像。
		$black = ImageColorAllocate($im, 238,238,238);	//设置背景颜色
	
		$values = array(
				mt_rand(0,$pw),  mt_rand(0,$ph),
				mt_rand(0,$pw),  mt_rand(0,$ph),
				mt_rand(0,$pw),  mt_rand(0,$ph),
				mt_rand(0,$pw),  mt_rand(0,$ph),
				mt_rand(0,$pw),  mt_rand(0,$ph),
				mt_rand(0,$pw),  mt_rand(0,$ph)
		);
		imagefilledpolygon($im, $values, 6, ImageColorAllocate($im, mt_rand(170,255),mt_rand(200,255),mt_rand(210,255)));	//設置干擾多邊形底圖
	
		/* 文字 */
		for ($i = 0; $i < strlen($authnum); $i++){
			$font = ImageColorAllocate($im, mt_rand(0,50),mt_rand(0,150),mt_rand(0,200));//设置文字颜色
			$x  = $i/$length * $pw + rand(1, 6);	//设置随机X坐标
			$y  = rand(1, $ph/3);					//设置随机Y坐标
			imagestring($im, mt_rand(4,6), $x, $y, substr($authnum,$i,1), $font); 
		}
		/* 加入干扰象素 */
		for($i=0; $i<$pnum; $i++){
			$dist = ImageColorAllocate($im, mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); //设置杂点颜色
			imagesetpixel($im, mt_rand(0,$pw) , mt_rand(0,$ph) , $dist); 
		} 
		/* 加入干擾線 */
		for($i=0; $i<$lnum; $i++){
			$dist = ImageColorAllocate($im, mt_rand(50,255),mt_rand(150,255),mt_rand(200,255)); //設置線顏色
			imageline($im,mt_rand(0,$pw),mt_rand(0,$ph),mt_rand(0,$pw),mt_rand(0,$ph),$dist);
		}
		ImagePNG($im);		//以 PNG 格式将图像输出到浏览器或文件
		ImageDestroy($im);	//销毁一图像
	}
	/** 檢查驗證碼
	* @param String $captcha	驗證碼
	* @param int 	$flag		驗證成功后 0:不清除session 1:清除session
	* @return boolean
	*/	
	public function check($captcha,$flag=1){
		if(empty($captcha)){
			return false;
		}else{
			if(strtoupper($captcha)==$this->captcha_session($this->sname)){	//檢測驗證碼
				if($flag==1){
					$this->captcha_session($this->sname,'');
				}
				return true;
			}else{
				return false;
			}
		}
	}
	
	/* 产生随机数函数
	* @param	int		$length	需要隨機生成的字符串數
	* @return	String
	*/
	private function random($length){
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZ23456789';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
		return $hash;
	}
	/** 驗證碼session處理方法
	* @param	String	$name	captcha session name
	* @param	String	$value
	* @return	String
	*/
	private function captcha_session($name,$value=null){
		if(isset($value)){
			if($value!==&#39;&#39;){
				$_SESSION[$name] = $value;
			}else{
				unset($_SESSION[$name]);
			}
		}else{
			return isset($_SESSION[$name])? $_SESSION[$name] : &#39;&#39;;
		}
	}
}	// class end
?>
Copy after login

demo

<?
	session_start();
	require_once(&#39;Captcha.class.php&#39;);
	$obj = new Captcha($sname);		# 創建Captcha類對象
									# $sname為保存captcha的session name,可留空,留空則為&#39;m_captcha&#39;
	$obj->create($length,$param);	# 創建Captcha并輸出圖片
									# $length為Captcha長度,可留空,默認為4
									/* $param = array(
											'width' => 13		captcha 字符寬度
											'height' => 18		captcha 字符高度
											'pnum' => 100		干擾點個數
											'lnum' => 2			干擾線條數
											)
											可留空
									*/
	$obj->check($captcha,$flag);	# 檢查用戶輸入的驗證碼是否正確,true or false
									# $captcha為用戶輸入的驗證碼,必填
									# $flag 可留空,默認為1 
									#		1:當驗證成功后自動清除captcha session
									#		0:當驗證成功后不清除captcha session,用於ajax檢查
?>
Copy after login

This article explains the relevant content about the php Captcha verification code class. For more related knowledge, please pay attention to the php Chinese website.

Related recommendations:

MySQL information_schema related content

View mysql database size, table size and last modification time

Detailed explanation of Sublime Text 2

The above is the detailed content of An explanation of the php Captcha verification code class. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

How to set session timeout in SpringBoot Session How to set session timeout in SpringBoot Session May 15, 2023 pm 02:37 PM

The problem was found in the springboot project production session-out timeout. The problem is described below: In the test environment, the session-out was configured by changing the application.yaml. After setting different times to verify that the session-out configuration took effect, the expiration time was directly set to 8 hours for release. Arrived in production environment. However, I received feedback from customers at noon that the project expiration time was set to be short. If no operation is performed for half an hour, the session will expire and require repeated logins. Solve the problem of handling the development environment: the springboot project has built-in Tomcat, so the session-out configured in application.yaml in the project is effective. Production environment: Production environment release is

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

What should I do if the php session disappears after refreshing? What should I do if the php session disappears after refreshing? Jan 18, 2023 pm 01:39 PM

Solution to the problem that the php session disappears after refreshing: 1. Open the session through "session_start();"; 2. Write all public configurations in a php file; 3. The variable name cannot be the same as the array subscript; 4. In Just check the storage path of the session data in phpinfo and check whether the sessio in the file directory is saved successfully.

What is the default expiration time of session php? What is the default expiration time of session php? Nov 01, 2022 am 09:14 AM

The default expiration time of session PHP is 1440 seconds, which is 24 minutes, which means that if the client does not refresh for more than 24 minutes, the current session will expire; if the user closes the browser, the session will end and the Session will no longer exist.

How to solve the problem that the Springboot2 session timeout setting is invalid How to solve the problem that the Springboot2 session timeout setting is invalid May 22, 2023 pm 01:49 PM

Problem: Today, we encountered a setting timeout problem in our project, and changes to SpringBoot2’s application.properties never took effect. Solution: The server.* properties are used to control the embedded container used by SpringBoot. SpringBoot will create an instance of the servlet container using one of the ServletWebServerFactory instances. These classes use server.* properties to configure the controlled servlet container (tomcat, jetty, etc.). When the application is deployed as a war file to a Tomcat instance, the server.* properties do not apply. They do not apply,

How to implement SMS login in Redis shared session application How to implement SMS login in Redis shared session application Jun 03, 2023 pm 03:11 PM

1. Implementing SMS login based on session 1.1 SMS login flow chart 1.2 Implementing sending SMS verification code Front-end request description: Description of request method POST request path /user/code request parameter phone (phone number) return value No back-end interface implementation: @Slf4j@ ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1. Verify mobile phone number if

See all articles