[Gllug] Unique id fields

Richard Jones rich at annexia.org
Sun Oct 12 12:36:45 UTC 2003


On Sat, Oct 11, 2003 at 07:01:33PM +0100, will wrote:
> On Sat, 2003-10-11 at 18:29, Daniel Andersson wrote:
> > first question, what do you need a unique id for?
> 
> User identification during/spanning sessions.  Shopping baskets mostly.
> 
> > and why one for each request?
> 
> I don't.  Just when the user first comes to the site (or a cookie
> expires).  The disadvantage of mod_unique_id is that it will generate a
> unique id for every request, wether one is needed of not.

For this I generally read 16 bytes from /dev/urandom and generate
a 32 character long cookie (from the hex representation of each byte).

Here's some Perl code:

sub generate_sessionid
  {
    my $length = 16;

    open RANDOM, "/dev/urandom"
      or die "Cannot open /dev/urandom: $!";

    my $bytes = "";
    croak "Reading random device returned != $length bytes: $!"
      if sysread (RANDOM, $bytes, $length) != $length;

    close RANDOM;

    my $token = '';
    for (my $i = 0; $i < $length; $i++) {
      my $b = ord (substr ($bytes, $i, 1));
      $token .= sprintf ("%02X", $b);
    }

    return $token;
  }

Here's some Objective Caml code (from mod_caml):

let generate_sessionid () =
  let chan = open_in_bin "/dev/urandom" in
  let len = 16 in
  let sessionid = String.create (len * 2) in
  for i = 0 to len-1 do
    let hex = Printf.sprintf "%02x" (input_byte chan) in
    String.blit hex 0 sessionid (i*2) 2
  done;
  close_in chan;
  sessionid


Rich.

-- 
Richard Jones. http://www.annexia.org/ http://freshmeat.net/users/rwmj
Merjis Ltd. http://www.merjis.com/ - all your business data are belong to you.
 All new technology is irrelevant until it is taken up by the public.

-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list