Snippet: Generate a Time-Based Key

I recently helped another developer looking for a way to only allow access to one site from an iframe on another. Ideally, this would be done with the HTTP_REFERRER header, but this isn't always set by the browser, and so would prevent too many people from seeing the content properly.

My solution was simply to use a time-based key that could be generated on the site containing the iframe and tested on the remote server before allowing access to the content.

This is a strategy used for secure VPN access, and also for other solutions, such as account registration authentication for sites, and so on.

This function can be adapted for most situations, and is reasonably secure (as long as you don't share the salt phrase):

function generate_timekey($salt, $window = 30)
{
 
    $time = microtime(true); // get current timestamp as float in seconds
 
    $seed = floor($time / $window); // gets a seed based on the current time, 
                                    // divided by the window, 
                                    // and then rounded down to an integer
 
    return md5($salt . $seed);
 
}
 
$timekey = generate_timekey("a random string of your choice");

The window is set in seconds - and the default is 30. It's probably a good idea not to go too much lower, especially when working on multiple servers as there may be some clock-drift which means that the time stamp won't match up.

Comments

Post new comment