Register

If this is your first visit, please click the Sign Up now button to begin the process of creating your account so you can begin posting on our forums! The Sign Up process will only take up about a minute of two of your time.

Results 1 to 10 of 10
  1. #1
    Senior Member rosland's Avatar
    Join Date
    Jul 2003
    Location
    Norway
    Posts
    1,944
    Member #
    2096
    Sessions and Cookie tutorial
    by Ståle Rosland

    First of all, what is meant by a 'session'?

    A 'session' is the word used to describe the period of time from a person sits down by his computer and starts surfing, until the time he's finished, turns off his browser and gets on with his real life.
    From a websites point of view, a session starts from the moment a user enters that site, navigates inside it and finally departs to another more interesting site. If he returns again, a new session has begun. It's not a continuation of the old one! However, there are ways to make the server recognize the visitor (ah, it's that guy again) and continue using the preferences that was set during his last visit.

    Internet uses a "stateless protocol" through HTTP. That means a server doesn't know, or keep track of, who's asking for a page or where that request is coming from. If three different persons from three different places in the world, visits the same site at the same time, and each view the same two pages, then the server sees that as 6 individual requests for pages from the server. It doesn't automatically keep track of who it is that's asking for the page.

    In other words, if your first page contained a form asking for the user to set his preferences for background color and other visual elements, then that information would be lost as soon as the visitor followed a link to another page. He would have to fill in a form like that on every page of the site if he wanted to keep the visual layout constant. The same goes for any other sort of individual handling, like a personal greeting or tailor made content based on client recognition from the server.

    This is what sessions and cookies are all about. They enable the server to recognize the individual asking for a new page. It will remember anything you've instructed it to remember. That means, if you look away from the personal tailoring capability it offers, it is also an excellent way of passing variables around your site, for whatever reason you might have.

    So then, let's get started!
    First, let me explain the difference between the two. A cookie is an information capsule containing minimum a name and a string value.
    (Think of it as a normal variable:
    $name="Sam";
    The equivalent cookie would be called "name" and hold the value "Sam".)
    A cookie can hold much more information, and I'll get back to that soon.

    After a session is started, it generates an ID that contains a name, and a value as well. The main difference between the two, is that cookie information is stored on the clients computer, while the session (name-value) gets passed from page to page by the server . All the additional session information (beyond the session ID), is stored on the server.

    As sessions use cookies when they can, I will start with describing the cookie first.


    ------COOKIE-START------

    A cookie is a text file stored on the clients computer (in a special format or encrypted), and can hold up to 4000 characters. Up to 20 cookies can be stored per website, and the client can store a maximum of 300 cookies.
    To set a cookie in your script (PHP), use:

    setcookie ( "name", "value", expire, "path", "domain", security );

    (It's important to remember that a cookie is part of the header information, and hence must be set before any other output is generated to the browser. Even a single blank space in front of your <?php tag, generates output to the browser (even though it doesn't show in the browser), and you will generate a "Error, headers already sent..." message)


    Only the name argument is mandatory!
    If you leave the rest (except value ) blank, they will get default values, and the cookie will expire the moment the user closes his browser.
    If you write:
    setcookie ('harry');
    then either nothing happens, or a cookie called 'harry' already in existence, will be deleted!
    Unlike variables in PHP, the cookie value won't set the value of 'harry' to NULL, but will actually erase the whole cookie!

    Notice no quote marks around expiry and security as these are integers!


    The arguments explained:

    • Name: Is exactly what it is. The name of the cookie.
    • Value: Whatever info you want the string to hold. Can't be much larger than approx 3,5 KB.
    • Expire: Specifies how long the cookie is allowed to live. A value of 0 (which is default) will make the cookie expire as soon as the browser is closed. Any other number signifies the number of seconds since midnight, january 1, 1970 GMT. You can use the time() argument (which is now) + a number of seconds to get the amount of time from now until you want it to expire (time()+(60*60*3)) equals 3 hours. You can also give it an absolute date through the mktime() function
    • Path: Defaults to the directory on the server where the cookie was generated/set. Outside this directory, it won't work. If you write "/" (forward slash), then it will be available for all directories on the server. If it says "/store", then it will only be available in the subdirectory 'store'.
    • Domain: Defaults to the current domain www.yoursite.com
      On large domains a subdomain can be specified (must contain at least two periods to be valid). Then the cookie will only be valid in that domain.
    • Security: Either 1 or 0.
      If 1 is set, then the cookie will only be sent via a secure HTTPS connection. The connection must already be running before the cookie can be sent! Default is 0.


    The advantage of cookies, is that they (can) persist after the session is finished. When the user returns later, he don't need to log in again (unless you want him to), doesn't need to reset preferences etc. The downside is that many users have cookies disabled in their browsers. If your site depends on cookies to work, then it won't work for them!

    That's what makes using sessions a good choice.
    -------COOKIE-END----------




    --------SESSION-START------

    If you want to keep a unique track record of an individual visiting your site, you have to assign some sort of ID to that person when he checks in. If you don't have any reason to track them in general, but want to protect your password-protected pages, then you will need to have some sort of authorization signature passed to the protected pages, when authorized people are navigating through them.
    You might also have a need for restricting access to certain functionality on a page or pages, without the need to re-authenticate every time an authorized person jumps to a new page.
    An example of the latter could be WDF:
    The first time you register and log in, WDF sets a cookie. The next time you visit, you are instantly recognized and don't need to log in again. If you're a moderator, you can (among other things) edit other people's posts. If you try to do that as a regular user, you won't be allowed. You don't have to re-verify who you are, the site keeps track of you as move along.
    If you're an admin, you will have access to menus other visitors can't see, even though you're loading the same page.

    If you just want to use it on password protected areas of your site, you can check for the presence and contents of a session variable. If it's not there, or with faulty values, you redirect visitors to the login page with a header(location: …) command.

    Now that you have a general idea of what you can use sessions for, let's look at how you start them and how you use that information on consecutive pages.

    To start a session in PHP, you use the command:
    session_start()
    The function needs no arguments.
    What it does, is to see whether there's an active session in progress already, or if it needs to start one. After a session has been started, you use the same command on top of each page that requires the session variables to execute its range of choices.
    The call to session_start must also be set at the top of the page, because of its cookie sending efforts. See note under cookies

    If there's no session in progress, the function call will start one, and assign a unique 32 figure number hash to a variable named PHPSESSID. (PHPSESSID by default, you can change this name in php.ini)
    It will also attempt to create a cookie named 'PHPSESSID' containing the number string of the session.
    The session is also stored in a temp directory on the server.

    After starting the session, you can assign variables to it. These variables will be stored on the server and be accessible on every page that starts with session_start(). The cookie is set with 0 as expire time, which means it will die as soon as the browser is closed. If you, on the other hand, leave the site and return to it (within a reasonable amount of time) the cookie will pick up again on the old session, and you can continue where you left.

    If the client has turned off cookie reception, PHP has an automatic work around installed. It will then try to send the message through either the URL via the GET method, or as POST data from a hidden form field if a form exists.
    The parser then has to rewrite the whole HTML script before presenting it to the browser, adding the session ID to every relative link on the page or hidden fields in existing forms. That means this latter method will take a bit longer to execute than if cookie transmission is possible.
    (This latest described capability will only work if PHP was configured with "-enable-trans-id" when compiled. If not, you have to rewrite all the links manually, or hope visitors accept cookies.)

    To register variables (make them globally available), you have to use the function call session_register('name'). Notice there's no $-symbol preceding the name. The variable is stored in the $_SESSION superglobal array. You can also add variables to the session array like this:

    $_SESSION['name']="Victor";

    You can also assign variable names that have yet not been assigned any value.
    The first time an active session encounters a variable assignment to that name, it will be incorporated and stored on the server for later session retrieval.
    (NB!
    Be aware that for this reason, having regular variables with the same name as session-registered variables might cause problems!
    If you have a session variable called 'count', and you use the variable $count in a different context on a consecutive page, that variable will reset the superglobal value.)


    A call to session_unregister('name') will delete the session_variable $name from the server.
    A call to session_destroy(), will delete the session from the server together with all its registered variables. The cookie might still be in the client's browser, but all the data associated with that session is gone.

    Whenever you want to retrieve session variables throughout your script, you use the superglobal:
    $_SESSION['name'].
    To see if a variable has been passed to the superglobal array, you can use:
    session_is_registered('name').
    This will return true/false and can be used in if() statements.
    ---SESSION-END------

    These are the most commonly used session functions. If you want to see the rest, visit http://no.php.net/manual/en/ref.session.php.

    #############

    A few notes towards the end. A call to session_start(), will try to send a cookie to the browser (containing the session id number). That cookie is used to navigate to the right session on the server, stored together with all registered variables. The cookie will expire when the browser closes, unless you tell it to behave differently using session_set_cookie_param().

    All session data stored on the server, will normally be erased after 30 minutes (default setting for most servers temp dir). If you want persistent data, you have to alter how session data is stored in PHP. If you have access to the php.ini file, you can alter the default directory for session data through the session.save_path directive in php.ini. You can also write your own functions for how to handle session data, by using set_session_save_handler(). You can then write all session data to your database, where it will be stored securely and available indefinitely, or until you erase it yourself. This is a bit more complicated, and I won't get into that now.

    Sessions and cookies can expand the functionality of your site tremendously and they're not too complicated to get started with. So go ahead and experiment!


    Hopefully, some of you may find this introduction useful, sessions and cookies canadd a lot of extra functionality to your sites, that otherwise would be impossible to obtain. :classic:


    PS.
    This forums member mass consists of everything from seasoned veterans to pure novices, with the majority somewhere in the middle (in accordance with standard "Gauss-distribution" of skills).
    If any of you merited programmers consider this banal, then remember it's intended for novices.
    S. Rosland

  2.  

  3. #2
    Member unclekyky's Avatar
    Join Date
    Sep 2003
    Posts
    62
    Member #
    2938
    When i downloaded it there was no extension so i had to put .zip on there to extract it, just so everyone knows.... I haven't had time to read it all but it's looking good!

  4. #3
    WDF Staff Wired's Avatar
    Join Date
    Apr 2003
    Posts
    7,656
    Member #
    1234
    Liked
    137 times
    Wow, 4 pages, that's long! If I get a chance later, I'll BBCode the sucka!
    The Rules
    Was another WDF member's post helpful? Click the like button below the post.

    Admin at houseofhelp.com

  5. #4
    Senior Member rosland's Avatar
    Join Date
    Jul 2003
    Location
    Norway
    Posts
    1,944
    Member #
    2096
    Thanks guys! :classic:

    It's a bit messy layout wise, so I'll try to rewrite at some point in the near future. I'm open for critique, if you're missing something, find any errors or generally think it stinks.

    (Make it constructive though, I'm a sensitive soul )
    S. Rosland

  6. #5
    WDF Staff Wired's Avatar
    Join Date
    Apr 2003
    Posts
    7,656
    Member #
    1234
    Liked
    137 times
    Did you ever rewrite it?
    The Rules
    Was another WDF member's post helpful? Click the like button below the post.

    Admin at houseofhelp.com

  7. #6
    Senior Member rosland's Avatar
    Join Date
    Jul 2003
    Location
    Norway
    Posts
    1,944
    Member #
    2096
    OK, I finally got around to it.

    The previous .rtf-attachment has been removed, and the original text has been reformatted with BB-code.

    If you see any typos or any explanatory errors, feel free to notify me.

    :glasses:
    S. Rosland

  8. #7
    Senior Member GeZe's Avatar
    Join Date
    Dec 2003
    Posts
    330
    Member #
    4381
    can you make sessions go over multiple domains? for instance if you have www.somesitelogin.com where the user logs in and then they go to www.somesitenews.com and they are still logged in.
    -GeZe

  9. #8
    Senior Member rosland's Avatar
    Join Date
    Jul 2003
    Location
    Norway
    Posts
    1,944
    Member #
    2096
    No, the cookie is only valid within the domain it's set.
    You can make it valid in child/subdomains though.

    It's a security issue, just like you can't get a list of files on a domain as long as it contains an index.page.
    S. Rosland

  10. #9
    Senior Member GeZe's Avatar
    Join Date
    Dec 2003
    Posts
    330
    Member #
    4381
    do you know how the MS .net passport works then?
    -GeZe

  11. #10
    Senior Member rosland's Avatar
    Join Date
    Jul 2003
    Location
    Norway
    Posts
    1,944
    Member #
    2096
    No, not really.

    But .NET PassPort is an additional MS technology (a web 'add on' layer so to speak) that is designed to follow its own protocol.

    It consists of its own modules that are responsible for cookie retrieval and authentication towards .NET Passport servers.

    Here's an excerpt from the MSDN online library:
    The Passport Manager is the component through which to interact with Microsoft® .NET Passport authentication servers, and the PassportIdentity object is the primary class through which to control the Passport Manager. The PassportIdentity object is a server-side object class for the .NET Passport single sign-in (SSI) service that uses cookies and query string data as intermediaries for querying a central data store.

    The Passport Manager has the following capabilities:
    • Provides an embedded encryption service that protects users' data without requiring additional work.
    • Handles all the .NET Passport cookie setting, parsing, and expiration logic so that participating Web sites do not need to access the .NET Passport-specific cookies using the HttpContext.Current.Request.Cookies collection.
    • Silently contacts the .NET Passport network servers to determine the current configuration of the network, and writes a local Component Configuration Document (CCD). Using the CCD, the PassportIdentity class has methods to provide participating sites with the appropriate URLs for the .NET Passport Update server, registration site, or privacy statement.
    So, in short, it's a system of its own.
    S. Rosland


Remove Ads

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
All times are GMT -6. The time now is 11:16 AM.
Powered by vBulletin® Version 4.2.3
Copyright © 2019 vBulletin Solutions, Inc. All rights reserved.
vBulletin Skin By: PurevB.com