treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Using Same Random Variable Twice

  • Hello,

    I am working on a site where I need to generate an authentication key that will be stored in both a session variable and a cookie. I generate this key using the following.
    $auth_key = sha1(microtime() . rand(10000, 99999 ));

    I then go on to store this value in a cookie and session variable like this...
    setcookie('auth_key', $auth_key, $expiration);
    $_SESSION['auth_key'] = $auth_key;


    The problem is that $auth_key generates a different value for the cookie and the session variable.
    Is there any way to turn the $auth_key (ie: random and microtime values) in to variable that does not change?
    In other words can PHP store a random variable in an unchanging variable?

    Any help would be much appreciated.

    Thanks,
    Sam
  • Here is the sample code I am using:

    <?php
    session_start();

    $auth_key = sha1(microtime() . rand(10000, 99999 ));

    setcookie('auth_key', $auth_key, time() + 1000);
    $_SESSION['auth_key'] = $auth_key;


    echo $_SESSION['auth_key'];
    ?>

    Using this, I am getting the same value for the session variable and the cookie data. You only set the auth_key variable once, and then use it in two places, so its value shouldn't change between the two times that you use it.

    I'm using Firecookie (a plugin for the Firefox Firebug plugin) to compare session/cookie data.