Cookie values getting duplicated - php

Currently I have a searchbar that saves the users search query inside a cookie. To do this I'm saving all the users inputs inside an array. Now the problem is that if the user types the same thing again, it gets duplicated and saves the duplicate value in the array as well. I want a way where the duplicate value doesn't get added to the cookie that has been set:
$input_search = json_decode(($this->input->post('keyword_search')));
if(isset($input_search))
foreach($input_search as $searchvals){
$searchvals->name = $searchvals->value;
unset($searchvals->value);
$searchval = json_encode($searchvals);
if (!isset($_COOKIE['lpsearch_history'])){
setcookie('lpsearch_history',$searchval,time() +3600 *365,'/');
}else {
$locations[] = json_decode($_COOKIE['lpsearch_history'], true);
$arrsearchval = json_decode($searchval, true);
if(!in_array($arrsearchval, $locations))
$locations[] = $arrsearchval;
$areas = json_encode($locations);
setcookie('lpsearch_history',$areas,time() +3600 *365,'/');
}
}
Now this gives an output something like this:
[[[[{"type":"community","devslug":"downtown-dubai","name":"Downtown Dubai"}],
{"type":"community","devslug":"downtown-dubai","name":"Downtown Dubai"}],
{"type":"community","devslug":"palm-jumeirah","name":"Palm Jumeirah"}],
{"type":"community","devslug":"palm-jumeirah","name":"Palm Jumeirah"}]

To prevent cookie being duplicated you need to match Cookie name and it's Content
if (isset($_COOKIE['Cookie_Name']) && $_COOKIE['Cookie_Name'] == "Cookie_Content") {
// do nothing cookie already existed and content match
} else {
setcookie('Cookie_Name', 'Cookie_Content', time()+1800, "/");
// create cookie which expire 30mins
}
Now if your cookie content come from "dynamic" source such as user input or rand() function you can store the cookie content in a $_SESSION and use that to verify cookie existance
if (isset($_COOKIE['Cookie_Name']) && $_COOKIE['Cookie_Name'] == $_SESSION['cookie_content']) {
// do nothing cookie already existed and content match
} else {
$cookie_content = rand(1000,999999); // random cookie content
$_SESSION['cookie_content'] = $cookie_content;
setcookie('Cookie_Name', $cookie_content, time()+1800, "/");
// create cookie which expire 30mins
}

Related

Delete a value from cookie with php

I am storing product id-s in a cookie with php. (These are the favorite products on a webshop.)
I added many products as favorit, so my cookie looks like: 12,55,120,43
What i know, that the $_COOKIE[$cookie_name] is not an array. (checked with is_array function)
How can i delete a product id from that cookie? I send the id that i want to delete with ajax to this php file:
if(isset($_POST['id']))
{
$id = intval($_POST['id']);
$cookie_name = "kedvenc_termek";
if(isset($_COOKIE[$cookie_name]))
{
echo $_COOKIE[$cookie_name];
}
}
Unset your cookie:
unset($_COOKIE[$cookie_name]);
Set your cookie null:
setcookie($cookie_name, null, -1, '/');
This should delete or invalidate cookie
// set the expiration date to one hour ago
setcookie($cookie_name, " ", time() - 3600);
?>
If I understand you correct you have a string stored in the cookie like 12,55,120,43 and you want to remove one of them using $_POST['id']?
Since it's a string I believe the best option is preg_replace() this gives you the benefit over str_replace that you can create a pattern to remove.
$id = $_POST['id'];
$cookie_name = "kedvenc_termek";
$_COOKIE[$cookie_name] = preg_replace("/\b(" . preg_quote($id) . ",)\b/", "", $_COOKIE[$cookie_name]);
echo $_COOKIE[$cookie_name];
If you want to store the new string in the cookie then be sure to do that before you echo the value since you can't set a cookie after an output.
Example: https://3v4l.org/RQH4o

PHP Add Updated Array to Current Session

Ok, so my aim is to add the current profile id ($for) to my session, the aim is for the system to understand which profiles have been viewed in the current session, thus adding to the array. Then it will check the array if it exists and will not show a popup on load as this only needs to happen once.
$for = $_GET['id'];
//GET PREVIOUSLY VIEWED IDS
$prevViewed = $_SESSION['viewedID'];
//THEN ADD THIS PAGE ID TO PREVIOUSLY VIEWED ARRAY
$prevViewed = $for;
//UPDATE SESSION WITH NEW ARRAY INC CURRENT PAGE
$_SESSION['viewedID'] = $prevViewed;
print_r($_SESSION['viewedID']);
How about something like this:
// Make sure that SESSION has the viewedID array
if (!isset($_SESSION['viewedID'])) $_SESSION['viewedID'] = array();
// Store this page in the array
$_SESSION['viewedID'][$for] = true;
You can then check if this page has been viewed with:
if (isset($_SESSION['viewedID'][$for]))
// it has been viewed
else
// it hasn't
I like it, looks like it would work a dream. However, I have fixed it now:
Add to Array the Profile which HAS been viewed...
//ADD THIS PAGE ID TO PREVIOUSLY VIEWED ARRAY
$prevViewed = $for;
//UPDATE SESSION WITH NEW ARRAY INC CURRENT PAGE
$_SESSION['viewedID'][] = $prevViewed;
Check the array for the Current Profile ID...
//CHECK IF CURRENT ID IS NOT IN ARRAY
if(isset($_SESSION['viewedID'])) {
if (!in_array($for, $_SESSION['viewedID'])) {
//PERFORM ACTION IF NOT IN ARRAY
} else {
//PERFORM ACTION IF IS IN ARRAY
}
}
Hope this helps someone.

Cookie array for Recently Viewed - need to extract data from array and cap cookie to 5 IDs

I am trying to create a recently viewed feature to a website. The idea is that you have a box in the right nav that shows your last 3 products viewed. You don't need to be logged it and it's no problem if the user clears cookies, it just starts over.
From what I've researched, the best way to do this is through a cookie array (as opposed to setting 5 cookies or keep adding cookies or doing something in mysql).
I'm having 2 problems:
First, the array keeps adding values, I want it to cap it at 3 values and from there drop the oldest, then add the newest. So, if you visited 7 product page IDs in this order: 100,200,300,400,500,600,150, the cookie should store the values (500,600,150). The first is the oldest of the 3, the last is the newest.
Second, I'm unclear of how to extract the array into something usable. The array is of ID numbers that I guess I need to query against the DB.
When I put this on the page:
COOKIE: <?php echo $cookie; ?>
I get this:
COOKIE: a:7:i:0;s:3:"100";i:1;s:3:"200";i:2;s:3:"300";i:3;s:3:"400";i:4;s:3:"500";i:5;s:3:"600";i:6;s:3:"150";}
This is my code:
//set product id
$product_id = [//some stuff here sets the product id]
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {
$cookie = array();
}
// add the value to the array and serialize
$cookie[] = $product_id;
$cookie = serialize($cookie);
// save the cookie
setcookie('recentviews', $cookie, time()+3600);
How do I first get the cookie to hold 3 values and drop the oldest?
What is the best way to extract those IDs into something I can put into a query?....str_replace?
This brings up another question, which is should I just put the URL, anchor text, and a couple of attributes of the product into the cookie and not look it up with php/mysql?
As always, thanks in advance.
Here was the answer I ended up figuring out myssef:
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {$cookie = array();}
// grab the values from the original array to use as needed
$recent3 = $cookie[0];
$recent2 = $cookie[1];
$recent1 = $cookie[2];

looping through url

I want to do a loop, normally it is done with while do for etc but when the process is big I came up with a solution to refresh the page by echoing a javascript to refresh the page for the next loop.
for example:
The page is http://localhost/index.php --> this preforms the first iteration with $i=1;
at the end of the script it will be redirected to http://localhost/index.php?i=$i++
if (!$_GET['i']){
$i = 1;
}else{
$i = $_GET['i'];
}
if ($i<500){
// proceed with $i = $_GET['i']
//then redirect to http://localhost/index.php?i=$i++
}else{
echo "done";
}
Now, consider a situation that the imput parameters come from a FORM to this script. (i.e. $parameter1 , $parameter2, $parameter3)
Then I have to pass them every time to new url (next iteration).
At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url?
At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url?
You can not with the bare redirect, but if you're talking about a specific user, you can do so by assigning those parameters as session variables Docs and then passing the session id as an additional parameter (or trust the user has cookies enabled).
function do_redirect($i, Array $parameters)
{
$i = (int) $i;
$parameters['i'] = $i; // save to session as well
$_SESSION['parameters'] = $parameters;
// redirect to http://localhost/index.php?i=$i&SID
}
if (is_form_request())
{
$parameters = get_form_parameters();
do_redirect(1, $parameters);
}
elseif (is_redirect_loop_request())
{
$parameters = $_SESSION['parameters'];
$i = $parameters['i'];
if ($i < 500)
{
do_redirect($i++, $parameters);
} else {
echo "done.";
}
}
Not to be rude, but both answers above are quite prone to security issues (but the session solution is the best one). As for the 'encryption' solution of #itamar: that's not exactly encryption... This is called 'Caesar cypher' (http://en.wikipedia.org/wiki/Caesar_cipher), which is indeed as safe as a paper nuclear bunker...
It can be much easier and safe as can be; do not save the iteration in the session, but in the database. For the next request, the only thing you have to do is get the iterator from the database and go on with whatever you want to do. Sessions can be stolen, meaning someone could let you iterate from, say, $i=10 a thousand times. It cannot be done when the iterator is stored in a secure database.

How do I use cookies to store users' recent site history(PHP)?

I decided to make a recent view box that allows users to see what links they clicked on before. Whenever they click on a posting, the posting's id gets stored in a cookie and displays it in the recent view box.
In my ad.php, I have a definerecentview function that stores the posting's id (so I can call it later when trying to get the posting's information such as title, price from the database) in a cookie. How do I create a cookie array for this?
**EXAMPLE:** user clicks on ad.php?posting_id='200'
//this is in the ad.php
function definerecentview()
{
$posting_id=$_GET['posting_id'];
//this adds 30 days to the current time
$Month = 2592000 + time();
$i=1;
if (isset($posting_id)){
//lost here
for($i=1,$i< ???,$i++){
setcookie("recentviewitem[$i]", $posting_id, $Month);
}
}
}
function displayrecentviews()
{
echo "<div class='recentviews'>";
echo "Recent Views";
if (isset($_COOKIE['recentviewitem']))
{
foreach ($_COOKIE['recentviewitem'] as $name => $value)
{
echo "$name : $value <br />\n"; //right now just shows the posting_id
}
}
echo "</div>";
}
How do I use a for loop or foreach loop to make it that whenever a user clicks on an ad, it makes an array in the cookie? So it would be like..
1. clicks on ad.php?posting_id=200 --- setcookie("recentviewitem[1]",200,$month);
2. clicks on ad.php?posting_id=201 --- setcookie("recentviewitem[2]",201,$month);
3. clicks on ad.php?posting_id=202 --- setcookie("recentviewitem[3]",202,$month);
Then in the displayrecentitem function, I just echo however many cookies were set?
I'm just totally lost in creating a for loop that sets the cookies. any help would be appreciated
Don't set multiple cookies - set one that contains an array (serialized). When you append to the array, read in the existing cookie first, add the data, then overwrite it.
// define the new value to add to the cookie
$ad_name = 'name of advert viewed';
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
$cookie = $_COOKIE['recentviews'];
$cookie = unserialize($cookie);
} else {
$cookie = array();
}
// add the value to the array and serialize
$cookie[] = $ad_name;
$cookie = serialize($cookie);
// save the cookie
setcookie('recentviews', $cookie, time()+3600);
You should not be creating one cookie for each recent search, instead use only one cookie. Try following this ideas:
Each value in the cookie must be
separated from the other with an
unique separator, you can use . ,
; or |. E.g: 200,201,202
When
retrieving the data from the cookie,
if it exists, use
explode(',',CookieName);, so you'll
end up with an array of IDs.
When adding
data to the cookie you could do,
again, explode(',',CookieName); to
create an array of IDs, then check if the
new ID is not in the array using
in_array(); and then add the value
to the array using array_push();.
Then implode the array using
implode(',',myString); and write
myString to the cookie.
That's pretty much it.

Categories