如何编写会话cookie以在移动到另一个页面时保留会话

时间:2019-05-05 12:35:32

标签: javascript php cookies session-cookies

在我的网站中,用户登录并移动到其他页面后,他们的会话丢失了,并返回上一页(创建会话的位置),该页面为空白,显然是因为会话丢失了

我有两页

  1. Account.php (登录后在其中创建会话的地方)
      <li class="nav-item">
        <a class="nav-link " href="Options.php">Go to options</a>
      </li>

    <?php 
      //Start of session
      session_start();

      //Setting up databse connection
      require_once 'databaseconnection.php'; 
      $conn = mysqli_connect($db_hostname, $db_username, $db_password,$db_database);
      if($conn->connect_error){
         die("CONNECTION FAILED:".$conn->connect_error);
      }

      //Getting phone number and pasword provided by user in the login page (Not included in this)
      if (isset($_POST['lpho']) &&          
          isset($_POST['lpass'])){ 
          $lpho   = get_post('lpho');  
          $lpass= get_post('lpass'); 

      //Getting user information from database
       $q="SELECT * FROM members WHERE phone='$lpho'";

       if($q) {
       //If record exists 
       $querymember = "SELECT * FROM members WHERE phone='$lpho' "; 
       $memberidentity = mysqli_query($conn,$querymember);
       //To get number of rows
       $rowsno = $memberidentity->num_rows;
       //To fetch specific member column from database as an array
       $memberrecords = $memberidentity->fetch_array(MYSQLI_NUM);

       $count=$rowsno;

       if($count>0){
       //$reqpass is user's password from the database which is specific to array no [7]
       $reqpass = $memberrecords[7];
       //If given password matches the required password...
       if($lpass==$reqpass){
         //Session details passed
         /*How do I put these in a cookie then load them on my next page */
         $_SESSION['lpho'] = $lpho;
         $_SESSION['lpass'] = $lpass;
       }
      } 
     }
    }
    ?>

  1. Options.php (会话在用户导航到该会话时死亡)

因此,我在总结中的问题是如何在Account.php中制作一个cookie,以保存lpho(电话)和lpass(密码),然后在出现以下情况时将其加载到Options.php中:用户导航到它。

<?php
    echo "This is the options page";
?>

1 个答案:

答案 0 :(得分:0)

在带有cookie的PHP中使用会话依赖于在页面标题中发送cookie。这意味着session_start()必须在页面的任何输出之前发生 (因为任何输出都会导致发送标头,并且每页只能发送一次)。在Account.php文件中,您要做的第一件事是输出<li>块,当您尝试使用headers already sent设置cookie时,这将导致session_start()错误。将session_start()移到每个PHP文件的开头,这应该可以解决此问题。例如,在此文件中:

<?php 
  //Start of session
  session_start();
?>
<li class="nav-item">
    <a class="nav-link " href="Options.php">Go to options</a>
</li>

<?php 
  //Setting up databse connection
  require_once 'databaseconnection.php'; 

请注意,以纯文本格式存储密码是一个非常糟糕的主意(在您的情况下,无论是在数据库中还是在服务器上的会话文件中)。您应该使用PHP password_hashpassword_verify函数来存储和检查密码。