2013-07-04 46 views
1

我想查看我的cookie過期時間。在PHP中查找Cookie到期時間?

我的代碼是這樣的:

setcookie('blockipCaptcha','yes',time() + (86400 * 7)); 

但我想看到Cookie的到期時間,每當我刷新頁面。如何做到這一點?

回答

4

除非您將該信息編碼爲cookie的一部分(瀏覽器,擁有此信息的用戶不會將其發送),否則無法獲取cookie到期時間。例如:

$expiresOn = time() + (86400 * 7); 
setcookie('blockipCaptcha','yes;expires=' . $expiresOn, $expiresOn); 

即使這樣,有人在理論上與cookie內容,所以你不能真正「信任」值,除非cookie內容也被加密與認證HMAC篡改。

如何簽名和驗證cookie的內容的一個例子:

$secretKey = ''; // this must be a per-user secret key stored in your database 
$expiresOn = time() + (86400 * 7); 
$contents = 'yes;expires=' . $expiresOn; 
$contents = $contents . ';hmac='. hash_hmac('sha256', $contents, $secretKey); 

當你回來的cookie的內容,去掉和驗證HMAC部分:

$contents = $_COOKIE['blockipCaptcha']; 

// I 'm doing this slightly hacky for convenience 
list ($contents, $hmac) = explode(';hmac=', $contents); 

if ($hmac !== hash_hmac('sha256', $contents, $secretKey)) { 
    die('Someone tampered with the contents of the cookie!'); 
}