search
HomeBackend DevelopmentPHP Tutorial菜鸟求教,如何将验证码的验证跟帐号密码加到一块去

求救啊附上源码

<?php require_once('Connections/kangci.php'); ?><?php$maxRows_a = 10;$pageNum_a = 0;if (isset($_GET['pageNum_a'])) {  $pageNum_a = $_GET['pageNum_a'];}$startRow_a = $pageNum_a * $maxRows_a;mysql_select_db($database_kangci, $kangci);$query_a = "SELECT * FROM zhanghao";$query_limit_a = sprintf("%s LIMIT %d, %d", $query_a, $startRow_a, $maxRows_a);$a = mysql_query($query_limit_a, $kangci) or die(mysql_error());$row_a = mysql_fetch_assoc($a);if (isset($_GET['totalRows_a'])) {  $totalRows_a = $_GET['totalRows_a'];} else {  $all_a = mysql_query($query_a);  $totalRows_a = mysql_num_rows($all_a);}$totalPages_a = ceil($totalRows_a/$maxRows_a)-1;$queryString_a = "";if (!empty($_SERVER['QUERY_STRING'])) {  $params = explode("&", $_SERVER['QUERY_STRING']);  $newParams = array();  foreach ($params as $param) {    if (stristr($param, "pageNum_a") == false &&         stristr($param, "totalRows_a") == false) {      array_push($newParams, $param);    }  }  if (count($newParams) != 0) {    $queryString_a = "&" . htmlentities(implode("&", $newParams));  }}$queryString_a = sprintf("&totalRows_a=%d%s", $totalRows_a, $queryString_a);?><?php// *** Validate request to login to this site.if (!isset($_SESSION)) {  session_start();}$loginFormAction = $_SERVER['PHP_SELF'];if (isset($_GET['accesscheck'])) {  $_SESSION['PrevUrl'] = $_GET['accesscheck'];}if (isset($_POST['test'])) {  $loginUsername=$_POST['test'];  $password=$_POST['textfield'];  $MM_fldUserAuthorization = "jibie";  $MM_redirectLoginSuccess = "";  $MM_redirectLoginFailed = "chatu2.php";  $MM_redirecttoReferrer = false;  mysql_select_db($database_kangci, $kangci);  	  $LoginRS__query=sprintf("SELECT name, password, jibie FROM zhanghao WHERE name='%s' AND password=md5('%s')",  get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername), get_magic_quotes_gpc() ? $password : addslashes($password));   $LoginRS = mysql_query($LoginRS__query, $kangci) or die(mysql_error());  $array=mysql_fetch_array($LoginRS);  $loginFoundUser = mysql_num_rows($LoginRS);   if ($loginFoundUser) {    $loginStrGroup  = mysql_result($LoginRS,0,'jibie');	 switch($array['jibie']){	  case 1: $MM_redirectLoginSuccess = "chatu2.php?recordID=$loginUsername"; break;		  case 2: $MM_redirectLoginSuccess = "321.php?recordID=$loginUsername"; break;	      case 3: $MM_redirectLoginSuccess = "Location.php?recordID=$loginUsername"; break;	 }    //declare two session variables and assign them    $_SESSION['MM_Username'] = $loginUsername;    $_SESSION['MM_UserGroup'] = $loginStrGroup;	          if (isset($_SESSION['PrevUrl']) && false) {      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	    }    header("Location: " . $MM_redirectLoginSuccess );  }  else {    header("Location: ". $MM_redirectLoginFailed );   }}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>动态案例站</title><style type="text/css"><!--body {	background-image: url(7981635_091456690000_2.jpg); 	background-repeat: no-repeat;}--></style></head><body><table width="100%" height="79%" border="0">  <tr>    <td height="140"> </td>  </tr></table><div align="center"><table width="300" height="150" border="0"><tr><td><form ACTION="<?php echo $loginFormAction; ?>" id="form1" name="form1" method="POST">  <p>    帐号:<input name="test" type="text" /></p>  <p>    <label>    密码:<input type="password" name="textfield" />    </label>  </p>  <p><script>function changeid(id){        document.getElementById(id).src ='yzm.php?'+Math.random(1);        }         </script>验证码<Input type="text" name="yz" id="yz"  size="8" />                                 <Img  title="看不清,换一张" id="pc" onclick="changeid('pc')" />     <label>    <input type="submit" name="Submit" value="登入" />    </label>  </p></form></tr></table></div><br></body></html><?phpmysql_free_result($a);?>

下面这一块是验证码……
<?phpsession_start();$nmsg="";for($i=0;$i<4;$i++){        $nmsg.=dechex(mt_rand(0,15));}       $_SESSION["code"]=$nmsg;header("Content-Type:image/jpeg");$width=75;$height=25;$img=imagecreatetruecolor($width,$height);$white=imagecolorallocate($img,255,255,255);imagefill($img,0,0,$white);$flag=false;if($flag){        $black=imagecolorallocate($img,0,0,0);        imagerectangle($img,0,0,$width-1,$height-1,$black);}for($j=0;$j<6;$j++){  $randcolor=imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));  imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$randcolor);}for($k=0;$k<100;$k++){  $rc=imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));  imagestring($img,1,mt_rand(1,$width),mt_rand(1,$height),"*",$rc);}for($s=0;$s<strlen($nmsg);$s++){         $randcolor=imagecolorallocate($img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));         imagestring($img,mt_rand(3,5),$s*$width/strlen($nmsg)+mt_rand(1,10),mt_rand(1,$height/2),$nmsg[$s],$randcolor);}imagejpeg($img);imagedestroy($img);?>


回复讨论(解决方案)

提交后检查验证码和$_SESSION["code"]是否对应就是了

if($_post['yz'])==$_session['code'])
这样写靠谱吗……

可以,不过$_post 应为 $_POST, $_session 应为 $_SESSION

报错了…………

既然报错就把错误信息贴出来

if($_POST['yz'] == $_SESSION['code'])

<?phpif (!isset($_SESSION)) {  session_start();}$loginFormAction = $_SERVER['PHP_SELF'];if (isset($_GET['accesscheck'])) {  $_SESSION['PrevUrl'] = $_GET['accesscheck'];}if (isset($_POST['test'])) {  $loginUsername=$_POST['test'];  $password=$_POST['textfield'];  $MM_fldUserAuthorization = "jibie";  $MM_redirectLoginSuccess = "";  $MM_redirectLoginFailed = "chatu2.php";  $MM_redirecttoReferrer = false;  mysql_select_db($database_kangci, $kangci);  	  $LoginRS__query=sprintf("SELECT name, password, jibie FROM zhanghao WHERE name='%s' AND password=md5('%s')",  get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername), get_magic_quotes_gpc() ? $password : addslashes($password));   $LoginRS = mysql_query($LoginRS__query, $kangci) or die(mysql_error());  $array=mysql_fetch_array($LoginRS);  $loginFoundUser = mysql_num_rows($LoginRS);   if($_POST['yz'] == $_SESSION['code']) {   if ($loginFoundUser) {    $loginStrGroup  = mysql_result($LoginRS,0,'jibie');	 switch($array['jibie']){	  case 1: $MM_redirectLoginSuccess = "chatu2.php?recordID=$loginUsername"; break;		  case 2: $MM_redirectLoginSuccess = "321.php?recordID=$loginUsername"; break;	      case 3: $MM_redirectLoginSuccess = "Location.php?recordID=$loginUsername"; break;	 }    //declare two session variables and assign them    $_SESSION['MM_Username'] = $loginUsername;    $_SESSION['MM_UserGroup'] = $loginStrGroup;    if (isset($_SESSION['PrevUrl']) && false) {      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	    }    header("Location: " . $MM_redirectLoginSuccess );  }   }  else {    header("Location: ". $MM_redirectLoginFailed );   }}?>

报的错是直接说我加的这行代码错误- -

另再求问下大大……做会员模块的话数据库的设计思路……如何实现一个帐号只允许一个IP登陆啊

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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool