Asked 8 years ago
21 Dec 2016
Views 1316
chirag

chirag posted

problem in $_COOKIE destroying in php

i am using $_COOKIE to remember some info for my website . but when i try to destroy it . it is not destroying some reason.

setting cookie

setcookie("myavatar","smile.png",time()+3600);


now unsetting it by unset and setcookie


<?php if(isset($_COOKIE['myavatar'])) { ?>
 <img src="<?php echo $_COOKIE['myavatar']); ?>" />
<?php 
unset($_COOKIE['myavatar']);
	setcookie("myavatar","",time()-3600);
 } ?>


see i try unset and than setcookie to past by time()-3600
so it should be destroyed by this two function :
1. unset($_COOKIE["cookiename"]) i try to unset as we do for varable

2.setcookie("cookiename","",time()-3600); i set cookie time to remain alive to past so it will destroy that way also

so point my problem pls . i am clueless now
shyam

shyam
answered Nov 30 '-1 00:00

as per you code . i think you sent header first and than try to change the cookie , which is not possible

let me explain little bit more detail about cookie

COOKIE stored in the client side. it will reside in user's computer.
and COOKIE will written through header sending procedure.
when page start to run they talk with browser by header.suppose is it request get or post it will be written in header which browser send to server.
and server also send header to browser to do action like send info about the output like content-type:html etc.. and to write cookie to user's pc .

when header already sent means start to output to browser . you cant send header again .
one time header sent in web page running life cycle.
so if you start to change cookie after header sent (started send html to view) , it will not work
so unset it at starting of webpage before of sending html

<?php if(isset($_COOKIE['myavatar'])) { 
 array_cookie['myavatar']=$_COOKIE['myavatar'];
unset($_COOKIE['myavatar']);
	setcookie("myavatar","",time()-3600);
 } ?>
<html>
<head>
....
</head>
<body>
 ...
<?php if(isset($array_cookie['myavatar'])) { 
 <img src="<?php echo $array_cookie['myavatar']); ?>" />

</html>


Post Answer