I want to provide a login on my site. I've been thinking about expanding the login system to store sessions via php sessions or cookies. I'm just having trouble figuring out when to use sessions or cookies, and what to read from when someone views page.

    I'm not exactly what you mean by

    I'm just having trouble figuring out when to use sessions or cookies, and what to read from when someone views page.

    Forgive me if I convey old knowledge to you...

    PHP sessions (along with the majority of Web development languages) employ cookies. However, these "temp" cookies are held only until the browser is closed.

    Also, with session cookies, the only data is a GUID. For example, this is what your browser sees:

    Set-Cookie: PHPSESSID=0160b348d7f308408e1c50449b42245d; path=/

    This enabled the server to remember you when you request other pages on the same Website.

    For example, Using:

    $_SESSION['MY_SITE_FULLNAME'] = $rows["fullname"];
    

    instructs the Web server to set a session cookie to your browser with the unique ID. When you go to subsequent pages in the Website, your browser will send this cookie back to the server with your session ID. The server can, at that point, replace:

    print $_SESSION['MY_SITE_FULLNAME'];
    

    with the fullname that is unique to your session.

    A big plus to this is that if you store alot of session information, the only data you need to send back and forth from a browser, is the ID. All the information about the session is stored on the Web server.

    Sessions typically (depending on your settings), timeout after a given amount of time (usually about 10 minutes by default). This means, even if your browser is open with the session cookie, upon retransmitting it to the server, the server has dumped the session info and a new session is created.

    This is a good feature for a login page where you want somebody to automatically logout after a given amount of time. However, sessions are not good, for example, if you are using them to store information such as shopping cart items, as the user may walk away for 15 minutes frantically looking for his or her credit card.

    Another example is the "remember me" feature that many sites employ. In this case, you'd want to store a cookie:

    setcookie ("MY_SITE_USER_ID", $value,time()+3600);

    In this case we actually stored data in a cookie that will persist after the browser has been closed. You could access this by:

    $userid = $_COOKIE["MY_SITE_USER_ID"];

    Hope this puts it all into perpective.

      Write a Reply...