how to unset cookie in PHP?

arboles picture arboles · May 10, 2012 · Viewed 70.1k times · Source

I need to figure out how to unset this cookie. Everything I tried so far has failed.

This is how I am currently unsetting it and it doesn't seem to work.

setcookie("user_id", $user_id, time() - 7200);

This is how I set it:

setcookie("user_id", $user_id, time() + 7200);

I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.

The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.

The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.

function set_session_from_cookie()
{
    if (isset($_SESSION['user_id'])) {
        echo '';
    } else {
        $_SESSION['user_id']=$_COOKIE['user_id'];
    }
}

Logout:

<?php
require'core.php';
session_destroy();

setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');

I set my cookie with the following code:

if ($rememberme == "on") {
    $user_id = mysql_result($query_run, 0, 'id');
    setcookie("user_id", $user_id, time() + 7200);
    $_SESSION['user_id'] = $user_id;
    redirect('home_page.php');
} else {
    if ($rememberme == "") {
        echo 'ok';
        $user_id = mysql_result($query_run, 0, 'id');
        echo $user_id;
        $_SESSION['user_id'] = $user_id;
        redirect('home_page.php');
    }
}

How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.

Answer

FThompson picture FThompson · May 10, 2012

Set the cookie's expiration date to a time in the past (like one second after epoch, for example).

setcookie("yourCookie", "yourValue", 1);

This will cause the cookie to expire.

1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.