SESSION实现登录实例
conncet.php:数据库连接文件
<?php
//数据库连接参数
$host = 'localhost';
$dbname = 'demo';
$username = 'root';
$pwd = 'root';
$dsn = "mysql:host=$host;dbname=$dbname";
try{
$pdo = new PDO($dsn,$username,$pwd);
}catch(PDOException $e){
die('连接失败:'.$e->getMessage());
}
?>
login.php:登录界面
<?php
if (isset($_SESSION['name'])){
echo '<script>alert("请不要重复登录");location.href="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>用户登录</title>
</head>
<body>
<h3>用户登录</h3>
<form action="dispatch.php?action=check" method="post" onsubmit="return isEmpty(this)">
<p>
<label for="username">账号</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="pwd">密码</label>
<input type="password" name="pwd" id="pwd">
</p>
<p>
<button>提交</button>
</p>
</form>
</body>
<script>
function isEmpty(form) {
if (form.username.value == ''){
alert('账号不能为空');
form.username.focus();
return false;
}
if (form.pwd.value == ''){
alert('密码不能为空');
form.pwd.focus();
return false;
}
return true;
}
</script>
</html>
dispatch.php:派发器,控制系统访问
<?php
header('content-type:text/html;charset=utf-8');
require '../connect.php';
$action = isset($_GET['action'])?$_GET['action']:'';
$action = strip_tags(strtolower(trim($action)));
switch ($action){
case 'login':
include 'login.php';
break;
case 'check':
include 'check.php';
break;
case 'logout':
include 'logout.php';
break;
default:
include 'index.php';
break;
}
index.php:首页
<?php
session_start();
header('content-type:text/html;charset=utf-8');
if (isset($_SESSION['name'])){
echo '用户:'.$_SESSION['name'].'已登录<br>';
echo '<a href="dispatch.php?action=logout">请退出</a>';
}else{
echo '<a href="dispatch.php?action=login">请登录</a>';
}
check.php:验证登录功能
<?php
session_start();
header('content-type:text/html;charset=utf-8');
if ($_POST){
$phone = trim($_POST['username']);
$pwd = md5(trim($_POST['pwd']));
$sql = 'SELECT * FROM `user` WHERE `phone`=:phone AND `pwd`=:pwd';
$stmt = $pdo->prepare($sql);
$stmt->execute(['phone'=>$phone,'pwd'=>$pwd]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result){
$_SESSION['name'] = $result['name'];
echo '<script>alert("登录成功");location.href="index.php";</script>';
}else{
echo '<script>alert("登录失败");history.back();</script>';
}
}
logout.php:退出功能
<?php
session_start();
header('content-type:text/html;charset=utf-8');
if (isset($_SESSION['name'])){
session_destroy();
echo '<script>alert("退出成功");location.href="index.php";</script>';
}else{
echo '<script>alert("请先登录");location.href="login.php";</script>';
}
手工抄写作业: