<?php if (isset($_SESSION['username'])){ echo "<script>alert('您已经登陆!');window.location.href='admin.php'</script>"; exit(); } ?> <!DOCTYPE html> <html> <head> <title>登陆界面</title> <meta charset="utf-8"> </head> <body> <form action="logincheck.php" method="post" accept-charset="utf-8"> <label>邮箱:</label> <input type="email" name="email" id="email"><br><br> <label>密码</label> <input type="password" name="password" value="" placeholder=""><br><br> <input type="submit" name="" value="登陆"> </form> </body> </html>
login.php页面
admin.php页面
<?php session_start(); if(!isset($_SESSION['username'])){ echo "<script>alert('请登陆!');window.location.href='login.php'</script>"; exit(); } $username=$_SESSION['username']; ?> <!DOCTYPE html> <html> <head> <title>管理界面</title> <meta charset="utf-8"> </head> <body> <p>欢迎您:<?=$username?></p> <a href="logout.php">退出</a> <form action="upload.php" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <input type="file" name="file" value="" placeholder="请选择上传的文件"> <input type="submit" name="submit" value="提交"> </form> </body> </html>
logout.php页面
<?php session_start(); if (!isset($_SESSION['username'])){ echo "<script>alert('你没登陆过,请先登陆!');window.location.href='login.php'</script>"; }else{ session_destroy(); //清楚会话。 echo "<script>alert('退出成功!');window.location.href='login.php'</script>"; } ?>
logincheck.php页面
<?php session_start(); //开启会话 $email=$_POST['email']; $password = $_POST['password']; include __DIR__."/pdo.php"; $sql = "SELECT * FROM `user` WHERE `email`=:email AND `password`=:password"; // echo $sql; $stmt = $dbh->prepare($sql); $stmt ->bindparam(':email',$email,PDO::PARAM_STR); $stmt ->bindparam(':password',$password,PDO::PARAM_STR); $stmt ->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user){ $_SESSION['username']=$user['name']; echo "<script>location.assign('admin.php')</script>"; }else{ echo "<script>alert('用户名密码错误');window.history.back()</script>"; } ?>
总结
COOKIE是客户端记录的,session是服务器端生成的。都是用来识别身份的,session相对存储在服务器安全性高些。