會(huì)話機(jī)制
1. cookie
http協(xié)議的無(wú)狀態(tài)問(wèn)題
服務(wù)器對(duì)用戶訪問(wèn)的跟蹤手段
$_COOKIE: 超全局變量數(shù)組
setcookie(): 設(shè)置客戶端cookie
常用操作: 創(chuàng)建/讀取/更新/刪除
2. session
session_start(): 啟動(dòng)新會(huì)話或者重用現(xiàn)有會(huì)話
session_id(): 獲取/設(shè)置當(dāng)前會(huì)話 ID
session_save_path(): 讀取/設(shè)置當(dāng)前會(huì)話的保存路徑
session_encode(): 將當(dāng)前會(huì)話數(shù)據(jù)編碼為一個(gè)字符串
session_decode: 解碼會(huì)話數(shù)據(jù)
session_destroy(): 銷毀一個(gè)會(huì)話中的全部數(shù)據(jù),僅清空而已
session_unset(): 釋放所有的會(huì)話變量
session_reset(): 回滾到上一次的會(huì)話
注意: 必須先執(zhí)行session_start()開(kāi)啟會(huì)話才生效,且之前不能有輸出
使用session的好處:能提高安全性,因?yàn)楸镜氐腸ookie只存儲(chǔ)服務(wù)session的ID,通過(guò)ID跟服務(wù)器交互獲取存儲(chǔ)再服務(wù)器的session的信息
login.php
<?php session_start(); //判斷是否重復(fù)登錄 if (isset($_SESSION['user_name'])){ header('location:index.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用戶登錄</title> <style> h3 { text-align: center; } div { width: 300px; height: 150px; /*background-color: lightblue;*/ margin: 0 auto; text-align: center; padding: 20px; border: 1px dashed #888; border-radius: 5%; } div input { border: none; border-bottom: 1px solid #333; } button:hover { cursor: pointer; background-color: lightblue; } .success { color: green; } .error { color: red; } </style> </head> <body> <h3>用戶登錄</h3> <div> <form name="user"> <p> <label>郵 箱: <input type="email" name="email" placeholder="name@example.com"> </label> </p> <p> <label>密 碼: <input type="password" name="password" placeholder="******"> </label> </p> <p> <button type="button" onclick="check(this.form)">登錄</button> </p> <!-- 提示信息占位符--> <p></p> </form> </div> <script> // 獲取表單 var user = document.forms.namedItem('user'); var tips = user.lastElementChild; function addEvent(ele,tips,msg) { ele.addEventListener('blur', function (){ if (this.value.trim().length === 0) { tips.classList.add('error'); tips.innerHTML = msg; this.focus(); } },false); ele.addEventListener('keydown', function () { tips.innerText = ''; },false); } // 給郵箱和密碼元素添加事件 addEvent(user.email, tips, '郵箱不能為空'); addEvent(user.password, tips, '密碼不能為空'); // 郵箱與密碼需要到數(shù)據(jù)表中驗(yàn)證,我們通過(guò)"Ajax"異步操作實(shí)現(xiàn) function check(form) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (request.readyState === 4 && request.status === 200) { // console.log(request.responseText); var data = JSON.parse(request.responseText); // 根據(jù)返回的狀態(tài),添加適當(dāng)?shù)腸lass樣式 if (data.status === 1) { // 移除之前的樣式,確?,F(xiàn)有樣式有效,如果之前沒(méi)有樣式也不會(huì)報(bào)錯(cuò)的 tips.classList.remove('error'); // 為成功添加特殊樣式,即綠色 tips.classList.add('success'); tips.innerText = data.message; // 2秒后跳轉(zhuǎn)到上一個(gè)頁(yè)面,即用戶列表頁(yè) setTimeout(function (){ // 跳轉(zhuǎn)到員工管理后臺(tái)首頁(yè) location.href = 'index.php'; },2000); } // 沒(méi)有更新或更新錯(cuò)誤采用同一個(gè)樣式 else { tips.classList.add('error'); tips.innerText = data.message; } } }; request.open('POST', 'check.php', true); request.setRequestHeader('content-type','application/x-www-form-urlencoded'); var data = 'email='+form.email.value.trim()+'&password='+form.password.value.trim(); request.send(data); } </script> </body> </html>
check.php
<?php session_start(); $status = 0;//默認(rèn)為0,0為錯(cuò)誤 $message = ''; if (empty($_POST['email'])){ $message = '郵箱不能為空'; exit(json_encode(['status'=>$status,'message'=>$message])); }else{ $email = strtolower(trim($_POST['email'])); } if (empty($_POST['password'])){ $message = '密碼不能為空'; exit(json_encode(['status'=>$status,'message'=>$message])); }else{ $password = trim($_POST['password']); } if ($email && $password){ $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); $stmt = $pdo->prepare('SELECT COUNT(*) FROM `user` WHERE `email`=:email AND `password`=:password'); if($stmt->execute(['email'=>$email,'password'=>$password])){ if($stmt->fetchColumn(0)>0 ){ $stmt= $pdo->prepare('SELECT `id`,`name` FROM `user` WHERE `email`=:email AND `password`=:password'); $stmt->execute(['email'=>$email,'password'=>$password]); $user = $stmt->fetch(PDO::FETCH_ASSOC); $_SESSION['user_id'] = $user['id']; $_SESSION['user_name'] = $user['name']; //修改狀態(tài)碼 $status = 1; $message = '登錄成功..'; exit(json_encode(['status'=>$status,'message'=>$message])); } else{ $message = '郵箱或密碼錯(cuò)誤'; exit(json_encode(['status'=>$status, 'message'=>$message])); } }else{ die(print_r($stmt->errorInfo()));//項(xiàng)目上線需隱藏報(bào)錯(cuò)信息 } }
logout.php
<?php session_start(); if (isset($_SESSION['user_name'])){ session_destroy();//銷毀存放在服務(wù)器的一個(gè)會(huì)話中的全部數(shù)據(jù) setcookie('PHPSESSID','',time()-3600,'/');//清空客戶端cookie數(shù)據(jù) header('location:login.php');//跳轉(zhuǎn)函數(shù)header() }
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)