在 PHP 登录脚本中使用会话和会话变量

2022-08-30 10:42:51

我刚刚完成创建整个登录并在PHP中注册systsem,但我的问题是我还没有使用任何会话。我是PHP的新手,我以前从未使用过会话。我想做的是,在用户注册并填写登录表单后,他们仍将停留在同一页面上。因此,如果会话logged_in则将有一部分,另一部分将处于其他状态(用户未登录,因此显示登录表单)。谁能告诉我如何开始?


答案 1

希望这有助于:)

开始会话,您需要在页面顶部或调用会话代码之前说出来

 session_start(); 

在会话中放置一个用户 ID 以跟踪谁登录了

 $_SESSION['user'] = $user_id;

检查是否有人登录

 if (isset($_SESSION['user'])) {
   // logged in
 } else {
   // not logged in
 }

查找已登录的用户 ID

$_SESSION['user']

所以在你的页面上

 <?php
 session_start();


 if (isset($_SESSION['user'])) {
 ?>
   logged in HTML and code here
 <?php

 } else {
   ?>
   Not logged in HTML and code here
   <?php
 }

答案 2

这是使用php的最简单的会话代码。我们正在使用3个文件。

登录.php

<?php  session_start();   // session starts with the help of this function 


if(isset($_SESSION['use']))   // Checking whether the session is already there or not if 
                              // true then header redirect it to the home page directly 
 {
    header("Location:home.php"); 
 }

if(isset($_POST['login']))   // it checks whether the user clicked login button or not 
{
     $user = $_POST['user'];
     $pass = $_POST['pass'];

      if($user == "Ank" && $pass == "1234")  // username is  set to "Ank"  and Password   
         {                                   // is 1234 by default     

          $_SESSION['use']=$user;


         echo '<script type="text/javascript"> window.open("home.php","_self");</script>';            //  On Successful Login redirects to home.php

        }

        else
        {
            echo "invalid UserName or Password";        
        }
}
 ?>
<html>
<head>

<title> Login Page   </title>

</head>

<body>

<form action="" method="post">

    <table width="200" border="0">
  <tr>
    <td>  UserName</td>
    <td> <input type="text" name="user" > </td>
  </tr>
  <tr>
    <td> PassWord  </td>
    <td><input type="password" name="pass"></td>
  </tr>
  <tr>
    <td> <input type="submit" name="login" value="LOGIN"></td>
    <td></td>
  </tr>
</table>
</form>

</body>
</html>

家.php

<?php   session_start();  ?>

<html>
  <head>
       <title> Home </title>
  </head>
  <body>
<?php
      if(!isset($_SESSION['use'])) // If session is not set then redirect to Login Page
       {
           header("Location:Login.php");  
       }

          echo $_SESSION['use'];

          echo "Login Success";

          echo "<a href='logout.php'> Logout</a> "; 
?>
</body>
</html>

注销.php

<?php
 session_start();

  echo "Logout Successfully ";
  session_destroy();   // function that Destroys Session 
  header("Location: Login.php");
?>

推荐