arboles arboles - 4 months ago 90
PHP Question

how to unset cookie in PHP?

i need to figure out how to unset this cookie. everything i have tried has failed so far.

this is how i am currently unsetting it, and it doesnt 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 not 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 my to no longer be able to logout.

Answer

The solution to this problem was that the I needed to set the correct path to unset the cookie since i was unsetting it from a different file that i originally set it in.

I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once i found the cookie inside my browser, the path was listed near the cookie. so i then set the path to the cookie like so

setcookie("user_id",$user_id,time()-1,"/social_learning/site_pages");

the last parameter is the path. and this worked.

my original set cookie looks like this.

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