博客列表 >SESSION实战-九期线上班(补作业)
SESSION实战-九期线上班(补作业)

- 皮皮的博客原创转载
- 2019年12月08日 19:13:43726浏览
index.php
<?php
session_start();
if (isset($_SESSION['user']) && $_SESSION['user']==='pipy'){
echo '用户:'.$_SESSION['user'].'已登录!<hr>';
echo '<a href="dispatch.php?action=logout">退出</a>';
}else{
echo '<a href="dispatch.php?action=login">请登录!</a>';
}
dispatch.php
<?php
session_start();
require __DIR__ . '/conn.php';
$action = isset($_GET['action']) ? $_GET['action'] : 'login';
$action = htmlentities(strtolower(trim($action)));
switch ($action) {
case 'login':
include __DIR__ . '/login.php';
break;
case 'check':
include __DIR__ . '/check.php';
break;
case 'logout':
include __DIR__ . '/logout.php';
break;
default:
include __DIR__ . '/index.php';
}
conn.php
<?php
//数据库连接参数
$db=[
'type'=>'mysql',
'host'=>'localhost',
'dbname'=>'pipysoft',
'username'=>'root',
'password'=>'123456',
];
//DSN
$dsn="{$db['type']}:host={$db['host']};dbname={$db['dbname']}";
try {
$pdo = new PDO($dsn, $db['username'], $db['password']);
//print_r($pdo);
}catch (PDOException $e){
die('Connection Failed: ' . $e->getMessage());
}
check.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = $_POST['user'];
$password = $_POST['password'];
$sql = 'SELECT * FROM `users` WHERE `user` = :user AND `password` = :password LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt->execute(['user'=>$user, 'password'=>$password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (false === $user) {
echo '<script>alert("用户名或密码错误或用户不存在!");history.back();</script>';
die;
}
$_SESSION['user'] = $user['user'];
echo '<script>alert("登录成功");location.assign("index.php");</script>';
exit;
} else {
die('请求错误!');
}
login.php
<?php
if (isset($_SESSION['user'])) {
echo '<script>alert("您已经登录,请不要重复登录!");location.assign("index.php");</script>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h3>用户登录</h3>
<form action="dispatch.php?action=check" method="post" onsubmit="return isEmpty();">
<p>
<label for="user">用户名:</label>
<input type="text" name="user" id="user">
</p>
<p>
<label for="password">密码:</label>
<input type="password" name="password" id="password">
</p>
<p>
<button>登录</button>
</p>
</form>
<script>
function isEmpty() {
var user = document.getElementById('user').value;
var password = document.getElementById('password').value;
if (user.length=== 0 || password.length===0) {
alert('用户名和密码不能为空');
return false;
}
}
</script>
</body>
</html>
logout.php
<?php
if (isset($_SESSION['user'])) {
session_destroy();
echo '<script>alert("退出登录成功!");location.assign("index.php");</script>';
} else {
echo '<script>alert("请登录!");location.assign("login.php");</script>';
}









声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。