title: How to keep a user logged into my website using a php session cookie
body: <p>Initially I came up with the following to see if a user is already logged in:</p>
  
  <pre><code>&lt;?php 
    session_start();
    if(!isset($_SESSION['sessionid'])) {
     header("Location: login_form.php");
    } else {
     echo "You are logged in";
    }
  ?&gt;
  </code></pre>
  
  <p><code>$_SESSION['sessionid']</code> is set when the user manually logs in.</p>
  
  <p>If the user checks "remember me" I set the session cookie's lifetime to be 10 years:</p>
  
  <pre><code>   $lifetime = 24*60*60*365*10; // 10 years
     setcookie(session_name(),session_id(),time()+ $lifetime,'/'); 
  </code></pre>
  
  <p>So now I need to figure out what to do on the server side....  Initially I was thinking of setting session.gc_maxlifetime to a high value so that the server's session data would live for a long time, but 10 years would be ridiculous.  Now I'm thinking I should store the session ID in the user table and query that against the session ID.  If there's a match, I'll auto log the user in.</p>
  
  <p>My question is:
   How do I get the session ID from the client?</p>
  
  <p>My understanding is that it will be available after I call session_start(), but only if the server's session data is still available.  If the session has expired (which happens depending on the value of session.gc_maxlifetime) a new session ID will get generated when session_start() is called.  This would be problematic as it wouldn't match the last session ID that I stored in the user table.</p>
  
  <p>So the ideas I have to read the session ID, after calling session_start() are:
  1) <code>$_SESSION['sessionid']</code>
  2) <code>$id = session_id();</code>
  3) <code>$_COOKIE["PHPSESSID"];</code></p>
  
  <p>1 and 2 won't work if the server has destroyed the session data, so I don't think I can use these.</p>
  
  <p>3 might work, but when I tried it (<code>echo $_COOKIE["PHPSESSID"];</code>) I was surprised because the session ID was appeared twice:
  the output was this:</p>
  
  <pre><code>htknitopug4b6bv4ql9050pfg6 //htknitopug4b6bv4ql9050pfg6
  </code></pre>
  
  <p>I simply expected the output to be <code>htknitopug4b6bv4ql9050pfg6.</code></p>
  
  <p>Can anyone explain the duplicate entry of the session ID?  If this behavior is consistent I could always read the first string into my database table.</p>