How can I improve this NONCE library for PHP?

Viewed 382

This is the first time I've worked with nonces, so I downloaded the script from http://fullthrottledevelopment.com/php-nonce-library. I did not like the code, especially because there's a chance of a legitimate request being treated as invalid because the function works in intervals of a defined amount of time (default is 300 seconds).

For example, we could be 299 seconds into the 300 seconds when the nonce is generated, so the nonce would only work for 1 second.

I modified the library into the following functions. What I did was check for the current interval and the previous interval by using nonce_create(time()-NONCE_DURATION)==$nonce. Are there ways to further improve the functions?:

define( 'NONCE_UNIQUE_KEY' , '123123' );
define( 'NONCE_DURATION' , 300 );

function nonce_create($time=false){
    if(!$time)
        $time=time();
    $i=ceil($time/(NONCE_DURATION));
    return substr(md5($i.NONCE_UNIQUE_KEY),-12,10);
}

function nonce_is_valid($nonce){
    if (nonce_create()==$nonce || nonce_create(time()-NONCE_DURATION)==$nonce)
        return true;
    return false;
}

Also, I have two questions regarding the original library:

  1. Why isn't NONCE_UNIQUE_KEY used? Did the author simply forget?
  2. Why does the author divide by two here: $i = ceil( time() / ( FT_NONCE_DURATION / 2 ) );, it only works for half the time then (I tried it)
1 Answers
Related