首先,将用户名与密码存储在数组中,当有用户登录时,从数组中取值参与检测,以判断用户名与密码是否有效。
登录与检测在同一个文件LoginFormAction中,代码:
<HTML> <BODY> <FORM METHOD="POST" ACTION="LoginFormAction.php"> <H2>用户登录</H2> <BR><BR> 用户名: <BR><INPUT TYPE="TEXT" NAME="username" SIZE="16"> <BR><BR> 密 码: <BR><INPUT TYPE="PASSWORD" NAME="password" SIZE="16"> <BR><BR> <BR><BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML> <!-- LoginFormAction.php <?php $passwords = array("name1" =>"pass1", "name2" =>"pass2"); if ($password == $passwords[$username]){ setcookie("username", $username, time()+1200); echo "<H2>登录成功.</H2>"; }else{ setcookie("username", "", time()-3600); echo "<H2>禁止登录:无效的用户名或密码</H2>"; } ?> -->
2,下面这段代码,通过一个自定义的php函数,实现用户登录检测。
可以检测用户名与密码长度、用户名与密码是否正确。
代码:
<?php //验证用户登录 //by www.jb200.com function validate_user ($username, $password){ return true; } // create empty array to store error messages $errors = array(); $p =& $_POST; if (count ($p) > 0){ if (!isset ($p['username']) || (trim ($p['username']) == '')){ $errors[] = 'You must enter a username.'; }elseif{ ((strlen ($p['username']) < 8) || (ereg ('[^a-zA-Z0-9]', $p['username']))){ $errors[] = '用户名无效,请输入至少8位的用户名,且只能包含字母与数字的组合。'; } if (!isset ($p['password']) || (trim ($p['password']) == '')){ $errors[] = 'You must enter a password.'; }elseif ((strlen ($p['password']) < 8) || (ereg ('[^[:alnum:][:punct:][:space:]]', $p['password']))){ $errors[] = '密码无效,请输入至少8位的密码,且只能包含字母、数字、标点与空格的组合。'; } if (count ($errors) == 0) { $r = validate_user ($p['username'], $p['password']); if ($r == false){ $errors[] = '登录失败,用户名与密码错误。'; } else { print ('<html><head><title>登录成功</title></head> <body><h1>祝贺你</h1><p>成功登录!</p> </body></html>'); exit; } } } ?> <html> <head><title>用户登录</title></head> <body> <h1>用户登录</h1> <?php if (count ($errors) > 0) { $n = count ($errors); for ($i = 0; $i < $n; $i++){ print '<br /><font color="red">' . $errors[$i] . '</font>'; } } ?> <form action="<?php print ($PHP_SELF); ?>" method="POST"> <table> <tr><td>Username:</td> <td><input type="text" name="username" value="<?php if (isset ($p['username'])) print $p['username']; ?>" /></td> </tr> <tr><td>Password:</td> <td><input type="text" name="password" value="<?php if (isset ($p['password'])) print $p['password']; ?>" /></td> </tr> <tr><td colspan="2"><input type="submit" name="submit"></td></tr> </table> <input type="hidden" name="__process_form__" value="1" /> </form> </body> </html>