5

I have this function to start a secure session:

function sec_session_start() {
    $session_name = 'sec_session_id'; // Set a custom session name
    $secure = false; // Set to true if using https.
    $httponly = true; // This stops javascript being able to access the session id. 

    ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
    $cookieParams = session_get_cookie_params(); // Gets current cookies params.
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"],     $cookieParams["domain"], $secure, $httponly); 
    session_name($session_name); // Sets the session name to the one set above.
    session_start(); // Start the php session
    session_regenerate_id(true); // regenerated the session, delete the old one.     
}

How do I set my cookies to expire whenever the user navigates away from my app or closes their browser? Basically, every time a user visits my app, they need to login again.

FastTrack
  • 8,810
  • 14
  • 57
  • 78
  • You may want to use a `$_SESSION` instead. `$_COOKIES` expire *only* after the expiration time. `$_SESSION`s end once the browser closes OR after their expiration time. – Matt Aug 09 '12 at 15:59
  • @Matt `$_SESSION` *uses* cookies to function. Those are the settings FastTrack is specifically setting here. Sessions are not a separate mechanism from cookies; they're just a clever use of cookies plus server-side storage. – VoteyDisciple Aug 09 '12 at 16:01
  • Here is a link to the same question http://stackoverflow.com/questions/3177364/destroy-php-session-on-page-leaving – Taylor Hakes Aug 09 '12 at 16:02
  • @VoteyDisciple last time I checked, `$_SESSION`s are server-side and `$_COOKIE`s are client-side. Can you provide documentation that I can read to clarify/prove your claim? I'm not arguing, I genuinely want to know. This would be news to me. – Matt Aug 09 '12 at 16:04
  • PHP session *data* is stored server-side (so the keys and values you put in your `$_SESSION` array are never sent to the browser). However, how does the server know which session is yours? Take a look at http://www.php.net/manual/en/session.idpassing.php for the two options and http://www.php.net/manual/en/session.examples.basic.php for basic information on session handling. – VoteyDisciple Aug 09 '12 at 16:11

1 Answers1

6

A lifetime of 0 (which is usually the default for session cookies) does precisely what you described. See http://us3.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime

VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97