session登陆验证
index.php
<?php
session_start();
if(isset($_SESSION['name'])){
echo $_SESSION['name'] . '欢迎您 ';
echo '<a href="dispatch.php?action=logout">退出</a>';
}else{
echo '<a href="dispatch.php?action=login">登陆</a>';
}
dispatch.php
<?php
session_start();
include __DIR__ . '/pablic/pdo.php';
$action = $_GET['action'] ?? 'login';
$action = htmlentities(strtolower(trim($action)));
switch($action){
case 'login' : include __DIR__ . '/pablic/login.php';
break;
case 'check' : include __DIR__ . '/pablic/check.php';
break;
case 'logout' : include __DIR__ . '/pablic/logout.php';
break;
default : include __DIR__ . '../index.php';
break;
}
pdo.php
<?php
$db = [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'film',
'user' => 'root',
'password' => 'root'
];
$dns = $db['type'] . ':host=' . $db['host'] . ';dbname=' . $db['dbname'];
try{
$pdo = new PDO($dns,$db['user'],$db['password']);
}catch(PDOException $e){
die('错误原因' . print_r($e -> getMessage(),true));
}
login.php
<?php
if(isset($_SESSION['name'])){
echo $_SESSION['name'] . '重复登陆啦';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>登陆</title>
</head>
<body>
<h3>立即登陆</h3>
<form action="../dispatch.php?action=check" method="post">
<p>
<label for="tel">账户:<input type="tel" name="tel" id=""></label>
</p>
<p>
<label for="password">密码:<input type="password" name="password" id=""></label>
</p>
<p>
<button>立即登陆</button>
</p>
</form>
</body>
</html>
check.php
<?php
if( !empty($_POST['tel']) && !empty(sha1($_POST['password'])) ){
$tel = $_POST['tel'];
$password = sha1($_POST['password']);
$sql = 'SELECT * FROM `user` WHERE `tel`=:tel AND `password`=:password LIMIT 1 ';
$stmt = $pdo -> prepare($sql);
$stmt -> execute(['tel'=>$tel, 'password'=>$password]);
$user = $stmt -> fetch(PDO::FETCH_ASSOC);
if(empty($user)){
echo '<script>alert("账户或密码错误");window.history.go(-1)</script>';
}else{
$_SESSION['name'] = $user['name'];
echo '<script>alert("登录成功");location.assign("../index.php");</script>';
exit;
}
}else{
echo '账户密码不能为空';
}
logout.php
<?php
if(isset($_SESSION['name'])){
session_destroy();
echo '<script>alert("退出成功");location.assign("../index.php")</script>';
}else{
echo '<script>alert("请先登陆");location.assign("dispatch.php?action=login.php")</script>';
}
PDO手抄