[ Team LiB ] Previous Section Next Section

21.7 Random Identifiers

If you ever need to track users through a site, you will need to assign unique identifiers. You can store all the information you know about the user in a database and pass the identifier from page to page either through links or with cookies. You will have to generate these identifiers randomly; otherwise, it is too easy for anyone to masquerade as a legitimate user. Fortunately, random identifiers are easy to generate.

Listing 21.9 illustrates how this works. A pool of characters to use in the session identifier is defined. Characters are picked randomly from the list to build a session identifier of the specified length. That identifier is used inside a link so that it is passed to the next page. This method works for any browser, even Lynx. Chapter 23 discusses the integration of this technique with a database.

It's very important to have random numbers here. Suppose you simply used the seconds on the clock. For an entire second, every session identifier would be the same. And it's very likely many people will be accessing a Web site during a single second. In Listing 21.9, I've used the time on the microsecond clock to seed the random generator, but even this allows the window of opportunity for getting a duplicate session identifier. One way to avoid this situation is to use a lockable resource that holds a seed—for example, a file. Once you lock the file, you can read the seed and write back a new one, at which point you are assured that two concurrent processes never get the same seed.

Listing 21.9 Generating a session identifier
<?php
    // SessionID
    // generates a session id
    function getSessionID($length=16)
    {
        // Set pool of possible characters
        $Pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $Pool .= "abcdefghijklmnopqrstuvwxyz";
        $lastChar = strlen($Pool) - 1;
        $sid = "";

        for($i = 0; $i < $length; $i++)
        {
            $sid .= $Pool[mt_rand(0, $lastChar)];
        }

        return($sid);
    }

    // Seed the generator
    mt_srand(100000000 * (double)microtime());

    if(isset($_REQUEST['sid']))
    {
        print("Old Session ID was {$_REQUEST['sid']}<br>\n");
    }

    $sid = getSessionID();

    print("<a href=\"{$_SERVER['PHP_SELF']}?sid=$sid\">");
    print("Get Another Session ID");
    print("</a>\n");
?>
    [ Team LiB ] Previous Section Next Section