index.phph文件
<?php
//开启会话
session_start();
var_dump( $_SESSION['name']);
if(isset($_SESSION['name']) && $_SESSION['name']==='admin'){
echo '用户:'.$_SESSION['name'].'已登录';
echo '<a href="dispatch.php?action=logout">请登录</a>a>';
}else{
// 未登录
echo '没有登录';
echo '<a href="login.php">请登录</a>';
}
login.php
<?php
// 防止用户重复登录
if (isset($_SESSION['name'])) {
echo '不要重复登录';
require __DIR__.'/index.php';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<form method="POST" action="check.php">
<label for="name">手机号:</label><br>
<input type="phone" name="phone" id="phone"><br>
<label for="password">密码:</label><br>
<input type="password" name="password" id="password"><br>
<button>提交</button>
</form>
</body>
</html>
check.php
<?php
session_start();
//链接数据库
require __DIR__ .'/connect.php';
// 1.判断用户的请求类型是否正确?
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 2.获取表单数据
$phone = $_POST['phone'];
$password = sha1($_POST['password']);
// 3. 用用户表user.dbf进行验证
$sql = 'SELECT * FROM `user` WHERE `phone` = :phone';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// 4. 判断验证的结果
if (false === $user) {
// 验证失败,返回上一下页面
echo '<script>alert("验证失败");history.back();</script>';
die;
}
echo $user['phone'];
// 验证成功,将用户的信息写到session
$_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 '退出成功';
} else {
// 要求用户先登录
echo '<script>alert("请先登录");location.assign("login.php");</script>';
}