无法使用PHP POST删除Cookie

时间:2015-11-17 20:23:44

标签: php post cookies

我尝试使用两个不同的POST命令设置和取消设置Cookie。我还没有能够实际删除我在第一次POST时设置的cookie。

if ($_POST['clockin'] == "Clock In") {  
    $cookie_name = "timein";
    $cookie_value = $id;
    setcookie($cookie_name, $cookie_value, time() + (86400), "/");
}

if ($_POST['clockout'] == "Clock Out") {    
    if (isset($_COOKIE[$cookie_name])) {
        unset($_COOKIE[$cookie_name]);
        setcookie($cookie_name, null, -1, '/');
    }
}

1 个答案:

答案 0 :(得分:1)

您只在第一个if语句中设置$cookie_name = "timein";,因此您无法在第二个语句中正确检查它以删除它,因为它在错误的范围内。您还应该在加入请求变量之前使用isset()来防止警告(如果它们不存在)。

// Set Cookie name outside if 
$cookie_name = "timein";

// Check if 'clockin' was submitted, then check the value
if (isset($_POST['clockin']) && $_POST['clockin'] == "Clock In") { 
    $cookie_value = $id;
    setcookie($cookie_name, $cookie_value, time() + (86400), "/");
}

// Check if 'clockout' was submitted, then check the value
if (isset($_POST['clockout']) && $_POST['clockout'] == "Clock Out") {    
    if (isset($_COOKIE[$cookie_name])) {
        unset($_COOKIE[$cookie_name]);
        setcookie($cookie_name, null, -1, '/');
    }
}