Can't update cookie

I tried to update cookie with php but it doesn’t work.
This is my code

<?php 
$id=58;
$cookiearray = $_COOKIE['content'];
$cookiearray = explode(",", $cookiearray); 
print_r($cookiearray);
$pos = array_search($id, $cookiearray);
echo '<br>Number 58 found at: ' . $pos; echo '<br>';
unset($cookiearray[$pos]); echo 'See if removed'; print_r($cookiearray); echo '<br><br>';
setcookie('content',$cookiearray,time()+31536000), '/');
echo 'Cookie values '.$_COOKIE['content']; ?>

I have cookie array $cookiearray that contains 3 numbers like that
Array ( [0] => 44 [1] => 57 [2] => 58 )

I goes well and ‘Number 58 found at: 2’

See if removed Array ( [0] => 44 [1] => 57 ) so it was successfully removed.
Then I do setcookie again and I get the old values when I echo it at the end.
Cookie values 44,57,58

Any idea why the cookie is not updated with new values 44,57?
Why setcookie doesn’t work?

You shouldn’t do any output before setcookie() call as it will not be able to send cookie header if output has been already started

You’re removing value from $cookiearray but not from $_COOKIE. These two arrays don’t linked between each other.

I tried without print and it doesn’t work.

 <?php 
$id=58;
$cookiearray = $_COOKIE['content'];
$cookiearray = explode(",", $cookiearray); 
// print_r($cookiearray);
$pos = array_search($id, $cookiearray);
// echo '<br>Number 58 found at: ' . $pos; echo '<br>';
unset($cookiearray[$pos]); // echo 'See if removed'; print_r($cookiearray); echo '<br><br>';
setcookie('content',$cookiearray,time()+31536000), '/');
// echo 'Cookie values '.$_COOKIE['content']; ?>

You can’t update cookie by unset command. I read you can only set it up again with new values.
That’s the why I haven’t do unset on the cookie but tried to set cookie again with new values.

You should understand that when you call setcookie() it actually affects contents of $_COOKIE array only on the next page load, when cookies will be received again

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.