user6362236 user6362236 - 4 months ago 9
PHP Question

have an array as a cookie value

hi every one i am having a php code and as you see i get id in it from another page. i want to save this id's in array based on cookies i did that too but i have a problem with it when i set timeout for example to 20 seconds and refresh page every 20 second it works fine but when i refresh it under 20 seconds it gives me this error
i do not know why could u please help i am stuck with it like 2 hours thank u


Fatal error: [] operator not supported for strings




<?php
$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;

$cookie_name = "favoritepost";

if ( isset($_COOKIE[$cookie_name]) ) {
$kookie = $_COOKIE[$cookie_name];
} else {
$kookie = array();
}
if ( ! in_array($ID, $kookie) ) {
$kookie[] = $ID;
}

setcookie($cookie_name, serialize($kookie), time() + (20), "/"); // 86400 = 1 day
?>
<html>




Answer

As per my last answer http://stackoverflow.com/a/38307347/2310830

<?php
$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;

$cookie_name = "favoritepost";

if ( isset($_COOKIE[$cookie_name]) ) {
    $kookie = unserialize($_COOKIE[$cookie_name]);
} else {
    $kookie = array();
}
if ( ! in_array($ID, $kookie) ) {
    $kookie[] = $ID;
}

setcookie($cookie_name, serialize($kookie), time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>