php用户登入与注销(session)
-
文件
-
index.php (主页)
<?php //开始会话 session_start(); header('Content-type:text/html;charset=utf-8'); if(isset($_SESSION['username']) ){ echo "您好!{$_SESSION['username']},欢迎回来!"; echo "<a href='logout.php'>注销</a>"; } else { echo "<a href='login.php'>请登入</a>"; } ?> <html> </p> 用户信息: <?php if(isset($_SESSION['username']) ){ echo $_SESSION['username']; } ?> </html>
-
login.php (登录页面)
<?php session_start(); header('Content-type:text/html;charset=utf-8'); if(isset($_SESSION['username']) ){ exit('您已经登入了,请不要重新登入'); } if(isset($_POST['submit'])){ //包含数据库连接文件 include 'conn.php'; $result=mysqli_query($conn,"select * from user where username ='{$_POST['username']}' ");//查出对应用户名的信息, while ($row=mysqli_fetch_array($result)) {//while循环将$result中的结果找出来 $dbusername=$row["username"]; $dbpassword=$row["password"]; } if(isset($_POST['username']) && isset($_POST['password']) && $_POST['username']== $dbusername && $_POST['password']==$dbpassword ){ $_SESSION['username']=$_POST['username']; header('location:skip.php?url=index.php&info=登入成功!3秒后跳转到首面'); } else { header('location:skip.php?url=login.php&info=对不起,用户名活密码填写错误!3秒后跳转到登入页面'); } } ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>请登入</title> </head> <body> <form method="post" action=""> 姓名:<input type="text" name="username" /> 密码:<input type="password" name="password"/> <input type="submit" name="submit" value="登入"/> </form> </body> </html>
-
conn.php (数据库连接文件)
<?php //数据库连接 $conn = mysqli_connect('localhost','root','root','tuiguang')or ('error'); ?>
-
logout.php (登出页面)
<?php session_start(); header('Content-type:text/html;charset=utf-8'); if(isset($_SESSION['username']) ){ session_unset();//free all session variable session_destroy();//销毁一个会话中的全部数据 setcookie(session_name(),'',time()-3600);//销毁与客户端的卡号 header('location:skip.php?url=index.php&info=注销成功,正在跳转!'); }else{ header('location:skip.php?url=index.php&info=注销失败,请稍后重试!'); } ?>
-
skip.php (跳转页面)
<?php if(!isset($_GET['url']) || !isset($_GET['info'])){ exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="refresh" content="3,URL=<?php echo $_GET['url'] ?>"/> <title>正在跳转中...</title> </head> <body> <div><?php echo $_GET['info'] ?></div> </body> </html>
-
index.php (主页)
-
数据库
- 数据库 tuiguang
- 用户名 root
- 密码 root
- 数据库地址 localhost
- 表 user
注意
会话使用前需先开始会话:session_start();
github地址:
https://github.com/eyunzhu/php/tree/master/login
目前评论:0