title: PHP empty session files generated by login system
body: <p>Recently I've noticed that many blank sessions are being created, I'm not sure why though as I believe I'm doing everything the correct way.</p>
  
  <p>At the moment we create a session when a user either <strong>logs in</strong> or <strong>registers</strong>, we then check whether a user is logged in with an <code>isset($_COOKIE['auth'])</code> that belongs to the session created during login or register.</p>
  
  <p>If that cookie is present then we start a session, this helps us avoid starting thousands of sessions for unregistered users and creating a huge amount of session files.</p>
  
  <p><strong>Session Settings:</strong></p>
  
  <p><em>php file</em></p>
  
  <pre><code>session_save_path("/home/user/sessions");
  session_set_cookie_params("86400", "/");
  session_name("auth");
  </code></pre>
  
  <p><em>php.ini</em></p>
  
  <pre><code>session.gc_maxlifetime = 90000
  session.cookie_lifetime = 90000
  session.use_trans_sid = 0
  session.use_only_cookies = 1
  </code></pre>
  
  <hr>
  
  <p><strong>Create Login Session</strong> (On Successful login)</p>
  
  <pre><code>session_start();
  session_regenerate_id(true);
  
  $_SESSION['userId'] = $userId;
  $_SESSION['created'] = time();
  
  session_write_close();
  header("Location: $_SERVER[HTTP_REFERER]");
  </code></pre>
  
  <hr>
  
  <p><strong>Checking whether a session should be resumed</strong></p>
  
  <p>We then check whether to start a session or not for a user based on whether the <code>auth</code> session cookie is set.</p>
  
  <p>It will only be set if the user has registered or logged in before:</p>
  
  <pre><code>if(isset($_COOKIE['auth'])){
      session_start();
      session_write_close();
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Check if user is logged in</strong></p>
  
  <p>To check if a user is logged in we then use a function:</p>
  
  <pre><code>function isAuthenticated(){
  
      if (!isset($_SESSION['userId']))
          return false;
      else
          return true;
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Log Out</strong></p>
  
  <pre><code>function logOut(){
      session_start();
      session_destroy();
      setcookie('auth', "", 0);
      unset($_SESSION);
      unset($_COOKIE['auth']); 
      return true;
  }
  </code></pre>
  
  <hr>
  
  <p>For some reason though I am getting lots of empty (filesize 0) session files in the session folder.</p>
  
  <p>Where are these coming from?</p>
  
  <p>Does <code>session_regenerate_id(true)</code> create a new session file and leave the old session file empty? That is the only reason I can think of for the empty session files?</p>