SESSION 登录实战
index.php
<?php
session_start();
//print_r($_SESSION);
if(isset($_SESSION['name'])){
echo '用户'.$_SESSION['name'].'已登录';
echo '<a href="dispatch.php?action=logout">退出登录</a>';
}else {
echo '<a href="dispatch.php?action=login">请登录</a>';
}
login.php
<?php
session_start();
if(isset($_SESSION['name'])){
echo '<script>alert("你已登录,请不要重复登录");location.assign("index.php");</script>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h2>用户登陆</h2>
<form action="dispatch.php?action=check" method="post">
<p>
用户名:<input type="text" name="name">
</p><p>
密码:<input type="password" name="pwd">
</p>
<p>
<input type="submit" value="提交">
</p>
</form>
</body>
</html>
dispatch.php
<?php
//开启session会话
session_start();
header("Content-type: text/html; charset=utf-8");
require __DIR__ . '/db.php';
$action = (isset($_GET['action'])) ? $_GET['action'] : login ;
$action = htmlentities(strtolower(trim($action)));
switch ($action){
case 'login':
header('location:login.php');
break;
case 'check':
include __DIR__ . '/check.php';
break;
case 'logout':
include __DIR__ . '/logout.php';
break;
default:
header('location:index.php');
}
check.php
<?php
//print_r($_SERVER);
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$name = $_POST['name'];
$pwd = md5($_POST['pwd']);
$sql = 'SELECT * FROM `user` WHERE `name` = :name AND `pwd` = :pwd LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt ->execute(['name' => $name,'pwd'=>$pwd]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if(false === $user){
echo '<script>alert("账号或密码错误");history.back();</script>';
die();
}
// setcookie('name',$name);
$_SESSION['name'] = $user['name'];
echo '<script>alert("登录成功");location.assign("index.php");</script>';
exit();
}else{
die("非法操作");
}
logout.php
<?php
if(isset($_SESSION['name'])){
session_destroy();
echo '<script>alert("退出成功");location.assign("index.php");</script>';
}else{
echo '<script>alert("请先登录");location.assign("login.php");</script>';
}
db.php
<?php
$db = [
'type' => 'mysql',
'host' => '127.0.0.1',
'dbname' => 'movies',
'username' => 'root',
'password' => 'root'
];
$dsn = "{$db['type']}:host={$db['host']};dbname={$db['dbname']}";
try{
$pdo = new PDO($dsn,$db['username'],$db['password']);
}catch(PDOException $e){
die('错误信息'.print_r($e->getMessage()));
}