search
HomeBackend DevelopmentPHP TutorialSolution to the inconsistent php session verification code and always display the last verification code

  1. $(".login").live('click',function(){

  2. var username=$(".input_user").val();
  3. var password=$( ".input_ps").val();
  4. var code=$('.input_checkcode').val();
  5. if(username==""){
  6. alert("Username cannot be empty");
  7. return false;
  8. }
  9. if(password==""){
  10. alert("Password cannot be empty");
  11. return false;
  12. }
  13. var URL="checkLogin.php?" ;

  14. var DATA="&username="+username+"&password="+password+"&code="+code;
  15. $.getJSON(URL+DATA,function(json){
  16. if(json.code=='code_error') {
  17. alert('Verification code error, please re-enter the verification code');
  18. }
  19. if(json.username=='true_u'&&json.password=='true_p'){
  20. //alert(json.username+"| "+username+'...1');
  21. window.location="index.php";
  22. }
  23. if(json.username=='error_u'||json.password=='error_p'){
  24. alert( "The username or password entered is incorrect, please check and log in again!");
  25. window.location="login.php";
  26. }
  27. });
  28. });
Copy code

Backend checkLogin.php key code:

  1. $code=$_GET['code'];
  2. if($code!=$_SESSION['captchaCode']['content'])
  3. {$adminInfo['code']='code_error' ;};
  4. if($row['username']==$username&&$row['password']==$password){
  5. $_SESSION['username']=$row['username'];
  6. $adminInfo['username']='true_u';
  7. $adminInfo['password']='true_p';
  8. mysql_close();
  9. }else
  10. if($row['username']!=$username){
  11. $adminInfo['username']='error_u';
  12. }
  13. if($row['password']!=$password){
  14. $adminInfo['password']='error_p';
  15. }
  16. //var_dump ($adminInfo);exit;
  17. echo json_encode($adminInfo);
Copy code

The details are as follows: checkCode.class.php//Verification code

  1. /*
  2. * Captcha Class base on PHP GD Lib
  3. * @author Design
  4. * @version 1.0
  5. * @copyright js8.in 2010 bbs.it-home.org
  6. * @demo
  7. * include('captchaClass.php');
  8. * $captchaDemo=new Captcha();
  9. * $captchaDemo->createImage();
  10. */
  11. class Captcha{
  12. //@Define the height of the verification code image
  13. private $height;
  14. //@Define the width of the verification code image
  15. private $width;
  16. //@Define the number of verification code characters
  17. private $textNum;
  18. //@Define the content of the verification code characters
  19. private $textContent;
  20. //@ Define character color
  21. private $fontColor;
  22. //@Define random text color
  23. private $randFontColor;
  24. //@Define font size
  25. private $fontSize;
  26. //@Define font
  27. private $fontFamily;
  28. //@ Define the background color
  29. private $bgColor;
  30. //@Define the random background color
  31. private $randBgColor;
  32. //@Define the character language
  33. private $textLang;
  34. //@Define the number of interference points
  35. private $noisePoint;
  36. / /@Define the number of interference lines
  37. private $noiseLine;
  38. //@Define whether to distort
  39. private $distortion;
  40. //@Define the distorted image source
  41. private $distortionImage;
  42. //@Define whether there is a border
  43. private $showBorder;
  44. //@Define verification code image source
  45. private $image;
  46. //@Constructor constructor
  47. public function Captcha(){
  48. $this->textNum=4;
  49. $this->fontSize=16;
  50. $ this->fontFamily='c:\windows\fontsSIMYOU.ttf';//Set the Chinese font, you can change it to the Linux directory
  51. $this->textLang='en';
  52. $this->noisePoint=30 ;
  53. $this->noiseLine=3;
  54. $this->distortion=false;
  55. $this->showBorder=false;
  56. }
  57. //@Set the image width
  58. public function setWidth($w){
  59. $this->width=$w;
  60. }
  61. //@Set the image height
  62. public function setHeight($h){
  63. $this->height=$h;
  64. }
  65. //@Set the character Number
  66. public function setTextNumber($textN){
  67. $this->textNum=$textN;
  68. }
  69. //@Set character color
  70. public function setFontColor($fc){
  71. $this->fontColor=sscanf ($fc,'#%2x%2x%2x');
  72. }
  73. //@Set the font size
  74. public function setFontSize($n){
  75. $this->fontSize=$n;
  76. }
  77. // @Set the font
  78. public function setFontFamily($ffUrl){
  79. $this->fontFamily=$ffUrl;
  80. }
  81. //@Set the character language
  82. public function setTextLang($lang){
  83. $this->textLang= $lang;
  84. }
  85. //@Set the picture background
  86. public function setBgColor($bc){
  87. $this->bgColor=sscanf($bc,'#%2x%2x%2x');
  88. }
  89. //@Set the number of interference points
  90. public function setNoisePoint($n){
  91. $this->noisePoint=$n;
  92. }
  93. //@Set the number of interference lines
  94. public function setNoiseLine($n){
  95. $this ->noiseLine=$n;
  96. }
  97. //@Set whether to display the border
  98. public function setDistortion($b){
  99. $this->distortion=$b;
  100. }
  101. //@Set whether to display the border
  102. public function setShowBorder($border){
  103. $this->showBorder=$border;
  104. }
  105. //@Initialization verification code picture
  106. public function initImage(){
  107. if(empty($this->width)) {$this->width=floor($this->fontSize*1.3)*$this->textNum+10;}
  108. if(empty($this->height)){$this->height =$this->fontSize*2;}
  109. $this->image=imagecreatetruecolor($this->width,$this->height);
  110. if(empty($this->bgColor)){
  111. $this->randBgColor=imagecolorallocate($this->image,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
  112. }else{
  113. $this->randBgColor=imagecolorallocate($this- >image,$this->bgColor[0],$this->bgColor[1],$this->bgColor[2]);
  114. }
  115. imagefill($this->image,0,0 ,$this->randBgColor);
  116. }
  117. //@Generate random characters
  118. public function randText($type){
  119. $string='';
  120. switch($type){
  121. case 'en':
  122. $ str='ABCDEFGHJKLMNPQRSTUVWXY3456789';
  123. for($i=0;$itextNum;$i++){
  124. $string=$string.','.$str[mt_rand(0,29)];
  125. }
  126. break;
  127. case 'cn':
  128. for($i=0;$itextNum;$i++) {
  129. $string=$string.','.chr(rand(0xB0, 0xCC)).chr(rand(0xA1,0xBB));
  130. }
  131. $string=iconv('GB2312','UTF-8',$string); //Convert encoding to utf8
  132. break;
  133. }
  134. return substr ($string,1);
  135. }
  136. //@Output text to verification code
  137. public function createText(){
  138. $textArray=explode(',',$this->randText($this->textLang) );
  139. $this->textContent=join('',$textArray);
  140. if(empty($this->fontColor)){
  141. $this->randFontColor=imagecolorallocate($this->image, mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
  142. }else{
  143. $this->randFontColor=imagecolorallocate($this->image,$this->fontColor[0],$this- >fontColor[1],$this->fontColor[2]);
  144. }
  145. for($i=0;$itextNum;$i++){
  146. $angle=mt_rand(-1,1)*mt_rand(1,20);
  147. imagettftext($this->image,$this->fontSize,$angle,5+$i*floor($this->fontSize*1.3),floor($this->height*0.75),$this->randFontColor,$this->fontFamily,$textArray[$i]);
  148. }
  149. }
  150. //@生成干扰点
  151. public function createNoisePoint(){
  152. for($i=0;$inoisePoint;$i++){
  153. $pointColor=imagecolorallocate($this->image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
  154. imagesetpixel($this->image,mt_rand(0,$this->width),mt_rand(0,$this->height),$pointColor);
  155. }
  156. }
  157. //@产生干扰线
  158. public function createNoiseLine(){
  159. for($i=0;$inoiseLine;$i++) {
  160. $lineColor=imagecolorallocate($this->image,mt_rand(0,255),mt_rand(0,255),20);
  161. imageline($this->image,0,mt_rand(0,$this->width),$this->width,mt_rand(0,$this->height),$lineColor);
  162. }
  163. }
  164. //@扭曲文字
  165. public function distortionText(){
  166. $this->distortionImage=imagecreatetruecolor($this->width,$this->height);
  167. imagefill($this->distortionImage,0,0,$this->randBgColor);
  168. for($x=0;$xwidth;$x++){
  169. for($y=0;$yheight;$y++){
  170. $rgbColor=imagecolorat($this->image,$x,$y);
  171. imagesetpixel($this->distortionImage,(int)($x+sin($y/$this->height*2*M_PI-M_PI*0.5)*3),$y,$rgbColor);
  172. }
  173. }
  174. $this->image=$this->distortionImage;
  175. }
  176. //@生成验证码图片
  177. public function createImage(){
  178. $this->initImage(); //创建基本图片
  179. $this->createText(); //输出验证码字符
  180. if($this->distortion){$this->distortionText();} //扭曲文字
  181. $this->createNoisePoint(); //产生干扰点
  182. $this->createNoiseLine(); //产生干扰线
  183. if($this->showBorder){imagerectangle($this->image,0,0,$this->width-1,$this->height-1,$this->randFontColor);} //添加边框
  184. imagepng($this->image);
  185. imagedestroy($this->image);
  186. if($this->distortion){imagedestroy($this->$distortionImage);}
  187. return $this->textContent;
  188. }
  189. }
  190. ?>
  191. code.php//new 一个对象,负责图片的创建以及验证码文本写入session
  192. session_start();
  193. header("Content-type:image/png");
  194. include('checkCode.class.php');
  195. $captcha5=new Captcha();
  196. //@设置验证码宽度
  197. //$captcha5->setWidth(200);
  198. //@设置验证码高度
  199. //$captcha5->setHeight(50);
  200. //@设置字符个数
  201. $captcha5->setTextNumber(4);
  202. //@设置字符颜色
  203. //$captcha5->setFontColor('#ffffff');
  204. //@设置字号大小
  205. //$captcha5->setFontSize(25);
  206. //@设置字体
  207. $captcha5->setFontFamily('c:\windows\fonts\comic.TTF');
  208. //@设置语言
  209. $captcha5->setTextLang('en');
  210. //@设置背景颜色
  211. //$captcha5->setBgColor('#000000');
  212. //@设置干扰点数量
  213. //$captcha5->setNoisePoint(600);
  214. //@设置干扰线数量
  215. //$captcha5->setNoiseLine(10);
  216. //@设置是否扭曲
  217. //$captcha5->setDistortion(true);
  218. //@设置是否显示边框
  219. $captcha5->setShowBorder(true);
  220. //输出验证码
  221. $code=$captcha5->createImage();
  222. $_SESSION['captchaCode']['content']=$code;
  223. //$_SESSION['captchaCode']['time']=microtime();
  224. ?>
复制代码

login.php//登陆页面,调用生成的验证码图片

  1. 验证码:
  • http://img.jbxue.com/admin/code.php
  • 复制代码


    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
    How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

    In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

    Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

    Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

    How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

    Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

    What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

    PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

    Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

    Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

    Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

    Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

    Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

    Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

    Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

    Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

    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

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor