post
poster: Jaguarstrike
description: PHP Expiring Hash Token
language: PHP
[download]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
function benchmark($closure)
{
    $start = microtime(true);
    $closure();
    $end   = microtime(true);
    return $end - $start;
}

class HashToken
{
    const SALT       = 'Whatever here. Make it random please.';
    const MAX_EXPIRY = 3600;
    const STD_EXPIRY = 300;
    
    public static function getToken($expTime = self::STD_EXPIRY)
    {
        $source = (time() + $expTime) . self::SALT;
        $hash = md5($source);
        return $hash;
    }
    
    public static function checkToken($token, $expectedExpiry = self::STD_EXPIRY)
    {
        if($expectedExpiry > self::MAX_EXPIRY)
        {
            $expectedExpiry = self::MAX_EXPIRY;
        }
        
        $i = 1;
        do
        {
            $source = (time() + $i) . self::SALT;
            $hash = md5($source);
            
            if($hash == $token)
            {
                return true;
            }
        }while(++$i <= $expectedExpiry);
        
        return false;
    }
}

$token = HashToken::getToken(2); //Token expires in two seconds
//sleep(1); //Pass
//sleep(2); //Fail

echo HashToken::checkToken($token) ? 'Passed' : 'Failed';
/*
echo benchmark(
    function() use ($token)
    {
        echo HashToken::checkToken($token) ? 'Passed' : 'Failed';
        echo PHP_EOL;
    }
);
*/