title: Session is destroyed on page refresh in PHP
body: <p>I am developing a web application using PHP in which a user initially has to sign in and view his content. I am using PHP sessions to maintain state. I encountered following problems:</p>
  
  <ol>
  <li>Although I started the session on each page and after relevent session variables are set, the session is destroyed each time the page is refreshed or when I browse the same URL on a different tab.</li>
  <li>I need the user to be redirected to his content page when the user browsed login page with he has already logged in.</li>
  </ol>
  
  <p>I'm really new to PHP, So I have no idea how to solve these problems. I referred several questions in the stackoverflow, but they all say that sessions are not destroyed on page refresh. I could not understand what's wrong with my page. Any solution with explaination is greatly appreciated.</p>
  
  <p><strong>Login page</strong></p>
  
  <pre><code>&lt;?php
  
  session_start();
  
  class Sessions{
          public static function setSessionState($userdata){
              unset($userdata['password']);
              unset($userdata['timestamp']);
              $_SESSION['user']=$userdata;
          }
      }
  
  if(isset($_POST['username']) &amp;&amp; isset($_POST['password'])){
          $dbcon = new DBConnection();
          $dbcon-&gt;connect();
          $username= strip_tags(stripslashes(trim($_POST['username'])));
          $password = strip_tags(stripcslashes($_POST['password']));
          echo "&lt;script&gt;alert($username);&lt;/script&gt;";
          $result = $dbcon-&gt;getUser($username,$password);
          if(mysqli_num_rows($result)==1){
              $user = $dbcon-&gt;getUserData($result);     #getUserData function accepts mysqli result as an input and returns a row(array) of user details.
              if(isset($user)){
                  Sessions::setSessionState($user);
                  header("location:index.php");
              }
              else{
                  echo "user variable is not set!!!";
              }
          }
          else if(mysqli_num_rows($result)==0){
              echo "Login error! Username or Password incorrect!";
          }
          else{
              die("Unknown Error occured!");
          }
      }
  ............
  </code></pre>
  
  <p><strong>Index page(in which user's private content is visible)</strong></p>
  
  <pre><code>&lt;?php 
  
      session_start();
  
      if(isset($_SESSION['user'])){
          print_r($_SESSION['user']);
      }
      else{
          echo "session variable not set";
      }
  ?&gt;
  </code></pre>
  
  <p>Thank you.</p>