Home >Backend Development >PHP Tutorial >A beautiful php verification code class (share)_PHP tutorial

A beautiful php verification code class (share)_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-21 14:59:251008browse

Directly upload the code:

Copy code The code is as follows:

//Verification code class
class ValidateCode {
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//Random factor
private $code;//Verification code
private $codelen = 4;//Verification code length
private $width = 130;//Width
private $height = 50;//Height
private $img;//Graphic resource handle
private $font;//Specified font
private $fontsize = 20;//Specified font size
private $fontcolor;//Specify font color
//Constructor initialization
public function __construct() {
$this->font = dirname(__FILE__).'/font/elephant.ttf ';//Please note that the font path must be written correctly, otherwise the picture cannot be displayed
}
//Generate random code
private function createCode() {
$_len = strlen($this->charset )-1;
for ($i=0;$i<$this->codelen;$i++) {
$this->code .= $this->charset[mt_rand(0, $_len)];
}
}
//Generate background
private function createBg() {
$this->img = imagecreatetruecolor($this->width, $this ->height);
$color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
imagefilledrectangle($this->img,0 ,$this->height,$this->width,0,$color);
}
//Generate text
private function createFont() {
$_x = $this- >width / $this->codelen;
for ($i=0;$i<$this->codelen;$i++) {
$this->fontcolor = imagecolorallocate($this- >img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x* $i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]);
}
}
//Generate lines and snowflakes
private function createLine() {
//Line
for ($i=0;$i<6;$i++) {
$ color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($this->img,mt_rand(0,$this->width) ,mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
// Snowflake
for ($i=0;$i<100;$i++) {
$color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)) ;
imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color );
}
}
//Output
private function outPut() {
header('Content-type:image/png');
imagepng($this-> ;img);
imagedestroy($this->img);
}
//Generate externally
public function doimg() {
$this->createBg();
$this->createCode();
$this->createLine();
$this->createFont();
$this->outPut();
}
//Get verification code
public function getCode() {
return strtolower($this->code);
}
}

Output Example:

Usage:
1. First save the verification code class as a file named ValidateCode.class.php;
2. Create a new file named captcha.php file to call this class;
captcha.php

Copy the code The code is as follows:

session_start();
require './ValidateCode.class.php'; //Include the class first, and modify the actual path according to the actual situation.
$_vc = new ValidateCode(); //Instantiate an object
$_vc->doimg();
$_SESSION['authnum_session'] = $_vc->getCode();/ /Save the verification code in SESSION

3. Quote it into the page, the code is as follows:
Copy the code The code is as follows:



4. A complete verification page, the code is as follows:
Copy the code The code is as follows:

session_start();
//On the page, you must first open the session,
//error_reporting(2047);
session_destroy();
//Remove the session so that it can be retrieved every time New session value;
//Using seesion works well and is very convenient
?>


session image verification example< ;/title><br><style type="text/css"><br>#login p{<br>margin-top: 15px;<br>line-height: 20px;<br>font-size : 14px;<br>font-weight: bold;<br>}<br>#login img{<br>cursor:pointer;<br>}<br>form{<br>margin-left:20px;<br>}<br></style><br></head> <br><body> <p><form id="login" action="" method="post"><br><p>This example is a session verification instance</p><br><p><br> <span>Verification code:</span><br><input type="text" name="validate" value="" size=10> <br><img title="Click to refresh" src= "./captcha.php" align="absbottom" onclick="this.src='captcha.php?'+Math.random();"></img><br></p><br><p><br><input type="submit"><br></p><br></form><br><?php<BR>//Print the previous session ;<BR>//echo "Previous session:<b>".$_SESSION["authnum_session"]."</b><br>";<br>$validate="";<br> if(isset($_POST["validate"])){<br>$validate=$_POST["validate"];<br>echo "What you just entered is: ".$_POST["validate"]." <br>Status: ";<br>if($validate!=$_SESSION["authnum_session"]){<br>//Determine whether the session value is consistent with the verification code entered by the user;<br>echo "< font color=red>Incorrect input</font>"; <br>}else{<br>echo "<font color=green>Passed verification</font>"; <br>}<br>} <br>?><br></p> </div> <br><strong>Full demo download: demo</strong> <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/328147.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/328147.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">Directly upload the code: Copy the code as follows: //Verification code class class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789' ;//Random factor private $code;...</span> </div> <div class="art_confoot"></div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="Solution to "The image cannot be displayed because of its own errors" when PHP generates verification code_PHP Tutorial" href="https://m.php.cn/faq/307068.html">Solution to "The image cannot be displayed because of its own errors" when PHP generates verification code_PHP Tutorial</a></span><span>Next article:<a class="dBlack" title="Solution to "The image cannot be displayed because of its own errors" when PHP generates verification code_PHP Tutorial" href="https://m.php.cn/faq/307070.html">Solution to "The image cannot be displayed because of its own errors" when PHP generates verification code_PHP Tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body><!-- Matomo --><script> var _paq = window._paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://tongji.php.cn/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '9']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); </script><!-- End Matomo Code --></html>