Hi,

I have a PHP project with login session and I would like to ask how can I expire the session automatically after x Time when the application is idle just like GoDaddy and many other websites?

Thanks,
Jassim

    How you 'expire' a session will depend on how your code stores a session and what behavior you mean exactly when you say 'expire.' In my case, I usually call [man]session_start[/man] in my code and then set some value in $_SESSION when a user logs in. Maybe something like this when a user successfully logs in:

    // user successfully logged in and we fetched their user info from a database into array $user_info
    
    session_start();
    $_SESSION["user_logged_in"] = TRUE;
    $_SESSION["current_user_id"] = $user_info["id"];
    $_SESSION["current_username"] = $user_info["username"];
    

    This relies on PHP's built-in session handling to store the session related data and maintain a session id. Understanding how sessions work in PHP takes a bit of effort to understand, but this would be time well spent because it's one of the most fundamental tasks you must perform to grant authenticated access to a web application.

    If I want to 'log someone out' or forcibily end their session, I can empty these values out:

    $_SESSION["user_logged_in"] = FALSE;
    unset($_SESSION["current_user_id"]);
    unset($_SESSION["current_username"]);
    

    Or, if you want this session to automatically expire after some period of time, it will automatically do so according to the PHP setting session.cache_expire. You may consider reading the PHP documentation on sessions here:
    http://php.net/manual/en/book.session.php

      6 days later

      Hi,
      In php basically you need to destroy the session and it is easy with this command.
      <code>
      <?php
      session_start();
      session_destroy();
      // now redirect to login page
      header("location:http://yourdomain.com/login.php");
      ?>
      </code>
      You need to study focus out maybe in jquery for this have a look in
      http://api.jquery.com/focusout/
      so catch the event and then send on above logout script and you are done.

        5 days later
        qadeer_ahmad;11046389 wrote:

        Hi,
        In php basically you need to destroy the session and it is easy with this command.

        <?php
        session_start();
        session_destroy();
        

        Except that it is not quite so easy. That only destroys the session data, as stated in the documentation for [man]session_destroy[/man]. The session still remains (simply use session_start again).

          johanafm;11046519 wrote:

          The session still remains.

          Right: you need [man]session_write_close[/man] to actually close the session.

            Write a Reply...