Answer the question
In order to leave comments, you need to log in
Why is the first id written to the cookie any number of times?
The essence of the task is to write the viewed lots on the site to the cookie, but only if the cookie does not yet contain the lot id. That is, all id in the cookie must be unique.
For me, for some reason, uniqueness is respected only for the second and subsequent entries in the cookie. That is, if I go to the page with id=1 with clean cookies and press f5, then all updates are written to the cookie. Those. the cookie will contain 1,1,1,1,1 etc. But starting from the second element, the uniqueness condition is already met. Those. if after the cookie already contains 1,1,1,1,1 go to a page with a different id , then it will already be written to the cookie only once.
if(isset($_COOKIE['lot_history'])) {
$lot_history = json_decode($_COOKIE['lot_history']);
if (!(array_search($_GET['id']-1, $lot_history))){
$lot_history[] = $_GET['id']-1;
$lot_history = json_encode($lot_history);
setcookie("lot_history", $lot_history, strtotime("+1 day"), "/");
}
}
else {
$lot_history = json_encode(array($_GET['id']-1));
setcookie("lot_history", $lot_history, strtotime("+1 day"), "/");
}
Answer the question
In order to leave comments, you need to log in
array_search can return either false or 0 (as the element's index). In your situation, just 0 is returned, which is interpreted as false in a non-strict check.
Just do a strict check...
if (array_search($_GET['id']-1, $lot_history) === false){
...
}
Thanks for answers. In order not to create a new question, I'll ask one more here, directly related to the topic:
If the user enters the id of a non-existent lot in the get request, then what is the best thing to do: do not write it in the cookie initially, or then simply do not display non-existing lots on the page for displaying lots?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question