brooksh Posted April 26, 2013 Share Posted April 26, 2013 I'm trying to set dynamic cookies. Why isn't it working? Here is my code. setcookie('mycookie[$id]',$id, time()+3600*24); Then to call it I use $_COOKIE['mycookie']['$id'] Quote Link to comment Share on other sites More sharing options...
Jessica Posted April 26, 2013 Share Posted April 26, 2013 '$id' is the literal string of '$id'. Not the value contained within $id. Of course, the same is true of your original set code, so it should still work. Just not how you think it will. Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 26, 2013 Share Posted April 26, 2013 (edited) That code works for me but, as Jessica stated, it won't be what you think it should be. To make the subkey of the array be the value of $id you could either use double quites when defining the cookie or concatenate the variable setcookie("mycookie[$id]", $id, time()+3600*24); // . . . OR setcookie('mycookie['.$id.']', $id, time()+3600*24); And then you need to remove the variable from inside the single quotes when referencing it as well echo "Saved value: " . $_COOKIE['mycookie'][$id]; But, again, the code you have will work, but the key would just be the string '$id' (i.e. dollar sign, letter 'i', letter 'd'). One reason you may not bee seeing the value is if you are trying to reference the value on the same page load as when you set it. Per the manual: http://php.net/manual/en/function.setcookie.php Once the cookies have been set, they can be accessed on the next page load . . . EDIT: Also, not sure why you are setting the array key and the value using the same variable. Seems like a waste to me. Edited April 26, 2013 by Psycho Quote Link to comment Share on other sites More sharing options...
brooksh Posted April 27, 2013 Author Share Posted April 27, 2013 Is there a better way? All I need is when a visitor visits a certain page and clicks on agree, it remembers it in a cookie and they won't have to click on the link again. But I want them to click agree on multiple pages. page1.php (agree yes then display page) page2.php (not agree, don't display page) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.