Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

IS there a simple way to generate a simple unique session ID? I tried some code that was given to me but it only generates a random digit between 0 and 60000, not the hex number that it was supposed to.
sub MakeID { # Seed the random generator srand($$|time); $sessionID=int(rand(60000)); # pack the time, process id, and random $session into a # hex number which will make up the sessin ID $session=unpack("H*", pack("Nnn", time, $$, $session)); return $session; } #Make ID

Replies are listed 'Best First'.
RE: Simple Session?
by merlyn (Sage) on May 03, 2000 at 18:39 UTC
    Besides the other good suggestions, if you need a cryptographically strong session key, you can use what Apache::Session uses:
    use MD5; sub generate_id { return substr(MD5->hexhash(time(). {}. rand(). $$. 'blah'), 0, 16) +; }

    -- Randal L. Schwartz, Perl hacker

      Says merlyn:
      sub generate_id { return substr(MD5->hexhash(time(). {}. rand(). $$. 'blah'), 0, 1 +6); }
      That {} seems like something of an oddity. I guess they threw it in on the theory that it couldn't hurt.

      (Part of me wants to say that [] would accomplish the same purpose, but with less memory. No doubt tye will not consider this funny. :-) )

Re: Simple Session?
by lhoward (Vicar) on May 03, 2000 at 17:36 UTC
    I made one small change to your code ($session to $sessionID in the pack call) and it seems to work fine. Sample output:
    sid="39102b7818bf0dc8"
    
    Program code:
    #!/usr/bin/perl -w my $s=MakeID(); print "sid="$s\"\n"; sub MakeID { # Seed the random generator srand($$|time); $sessionID=int(rand(60000)); # pack the time, process id, and random $session into a # hex number which will make up the sessin ID $session=unpack("H*", pack("Nnn", time, $$, $sessionI +D)); return $session; } #Make ID
Re: Simple Session?
by turnstep (Parson) on May 03, 2000 at 17:08 UTC
    I've always liked "$^T$$" which is pretty darn unique, as the system is not likely to have two processes with the same number at the exact same time. (If it does, your system has some *real* problems!) You could even subtract, say, the time from 2 weeks before the script ran to get a smaller number.