为什么不使用加密?
我受到这个问题的启发,这使得安全地使用到期日期成为可能。
$time = time() + 90;
$key = "a private password";
echo "Expiration time = {$time}<br/>";
$code = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $time, MCRYPT_MODE_CBC, md5(md5($key))));
echo "Sharable encrypted code = {$code}<br/>";
(.......一段时间后,您的 $code 又回来了)
$time = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($code), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
echo "Decoded time is {$time}...";
if ($time < time()) {
echo "Code has expired<br/>";
} else {
echo "Code is OK<br/>";
}
这将输出:
Expiration time = 1347312816
Sharable encrypted code = ioVqtqZud+iexObaGBF418i0gHKHshjsy+mj+oM4KMw=
Decoded time is 1347312816...Code is OK
使用这种方法,您需要两个功能:
// returns a code valid $duration seconds
function createKey($duration) {
$key = "a private password";
$time = time() + $duration;
$code = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $time, MCRYPT_MODE_CBC, md5(md5($key))));
return $code;
}
// returns true if code is still valid
function checkKey($code)
{
$key = "a private password";
$time = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($code), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return ($time >= time());
}