PHP簡(jiǎn)單登錄退出代碼
所屬欄目: 網(wǎng)站開(kāi)發(fā) | 更新時(shí)間:2016-3-25 | 閱讀:5173 次
登錄頁(yè)面
login.html 負(fù)責(zé)收集用戶(hù)填寫(xiě)的登錄信息。
<fieldset> <legend>用戶(hù)登錄</legend> <form name="LoginForm" method="post" action="login.php" onSubmit="return InputCheck(this)"> <p> <label for="username" class="label">用戶(hù)名:</label> <input id="username" name="username" type="text" class="input" /> <p/> <p> <label for="password" class="label">密 碼:</label> <input id="password" name="password" type="password" class="input" /> <p/> <p> <input type="submit" name="submit" value=" 確 定 " class="left" /> </p> </form> </fieldset>
javascript 檢測(cè)及 CSS 樣式可參考 reg.html,本部分略去,可直接查看最后附錄的完整代碼。
登錄處理
login.php 負(fù)責(zé)處理用戶(hù)登錄與退出動(dòng)作。
//登錄 if(!isset($_POST['submit'])){ exit('非法訪問(wèn)!'); } $username = htmlspecialchars($_POST['username']); $password = MD5($_POST['password']); //包含數(shù)據(jù)庫(kù)連接文件 include('conn.php'); //檢測(cè)用戶(hù)名及密碼是否正確 $check_query = mysql_query("select uid from user where username='$username' and password='$password' limit 1"); if($result = mysql_fetch_array($check_query)){ //登錄成功 $_SESSION['username'] = $username; $_SESSION['userid'] = $result['uid']; echo $username,' 歡迎你!進(jìn)入 <a href="my.php">用戶(hù)中心</a><br />'; echo '點(diǎn)擊此處 <a href="login.php?action=logout">注銷(xiāo)</a> 登錄!<br />'; exit; } else { exit('登錄失敗!點(diǎn)擊此處 <a href="javascript:history.back(-1);">返回</a> 重試'); }
該段代碼首先確認(rèn)如果是用戶(hù)登錄的話,必須是 POST 動(dòng)作提交。然后根據(jù)用戶(hù)輸入的信息去數(shù)據(jù)庫(kù)核對(duì)是否正確,如果正確,注冊(cè) session 信息,否則提示登錄失敗,用戶(hù)可以重試。
該段代碼需要在頁(yè)面開(kāi)頭啟用 session_start() 函數(shù),參見(jiàn)下面 退出處理 代碼部分。
退出處理
處理用戶(hù)退出的代碼跟處理登錄的代碼都在 login.php 里。
session_start(); //注銷(xiāo)登錄 if($_GET['action'] == "logout"){ unset($_SESSION['userid']); unset($_SESSION['username']); echo '注銷(xiāo)登錄成功!點(diǎn)擊此處 <a href="login.html">登錄</a>'; exit; }
該段代碼在處理用戶(hù)登錄的代碼之前,只允許以 login.php?action=logout 的方式訪問(wèn),其他方式都認(rèn)為是檢測(cè)用戶(hù)登錄。具體邏輯參看附錄完整代碼。
用戶(hù)中心
my.php 是用戶(hù)中心,列在教程里作為用戶(hù)登錄檢測(cè)參考。
<?php session_start(); //檢測(cè)是否登錄,若沒(méi)登錄則轉(zhuǎn)向登錄界面 if(!isset($_SESSION['userid'])){ header("Location:login.html"); exit(); } //包含數(shù)據(jù)庫(kù)連接文件 include('conn.php'); $userid = $_SESSION['userid']; $username = $_SESSION['username']; $user_query = mysql_query("select * from user where uid=$userid limit 1"); $row = mysql_fetch_array($user_query); echo '用戶(hù)信息:<br />'; echo '用戶(hù)ID:',$userid,'<br />'; echo '用戶(hù)名:',$username,'<br />'; echo '郵箱:',$row<'email'>,'<br />'; echo '注冊(cè)日期:',date("Y-m-d", $row['regdate']),'<br />'; echo '<a href="login.php?action=logout">注銷(xiāo)</a> 登錄<br />'; ?>