P粉5738097272023-08-22 13:18:23
This is the simplest session code written in PHP. We used 3 files.
login.php
<?php session_start(); // 使用此函数启动会话 if(isset($_SESSION['use'])) // 检查会话是否已存在,如果存在则直接重定向到主页 { header("Location:home.php"); } if(isset($_POST['login'])) // 检查用户是否点击了登录按钮 { $user = $_POST['user']; $pass = $_POST['pass']; if($user == "Ank" && $pass == "1234") // 用户名默认为“Ank”,密码默认为1234 { $_SESSION['use']=$user; echo '<script type="text/javascript"> window.open("home.php","_self");</script>'; // 登录成功后重定向到home.php } else { echo "无效的用户名或密码"; } } ?> <html> <head> <title> 登录页面 </title> </head> <body> <form action="" method="post"> <table width="200" border="0"> <tr> <td> 用户名</td> <td> <input type="text" name="user" > </td> </tr> <tr> <td> 密码 </td> <td><input type="password" name="pass"></td> </tr> <tr> <td> <input type="submit" name="login" value="登录"></td> <td></td> </tr> </table> </form> </body> </html>
home.php
<?php session_start(); ?> <html> <head> <title> 主页 </title> </head> <body> <?php if(!isset($_SESSION['use'])) // 如果会话未设置,则重定向到登录页面 { header("Location:Login.php"); } echo $_SESSION['use']; echo "登录成功"; echo "<a href='logout.php'> 退出</a> "; ?> </body> </html>
logout.php
<?php session_start(); echo "成功退出"; session_destroy(); // 销毁会话 header("Location: Login.php"); ?>
P粉3480889952023-08-22 12:03:57
To start a session, you need to say this at the top of the page or before calling the session code
session_start();
Put user ID into session to track who is logged in
$_SESSION['user'] = $user_id;
Check if anyone is logged in
if (isset($_SESSION['user'])) { // 已登录 } else { // 未登录 }
Find the ID of the logged in user
$_SESSION['user']
On your page
<?php session_start(); if (isset($_SESSION['user'])) { ?> 已登录的HTML和代码在这里 <?php } else { ?> 未登录的HTML和代码在这里 <?php }