Delete a value from cookie with php - 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

Related

Cookie values getting duplicated

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
}

PHP make a variable have permanent value

I use a variable, value of which is a random string. Every time I refresh the page, that string changes. All good but I need to echo also the random string that was also generated before the new refresh, in other words store that string into a permanent let's say variable. Example: 12345 is generated, reload, abcde is generated but I want 12345 to be echoed as well... How can I do this? Thanks
You can put that variable value in the php SESSION
<?php session_start();
$str = "";
if(!isset($_SESSION['var1']) || empty($_SESSION['var1']))
{
$str = ... // random a string
$_SESSION['var1'] = str; // save in session
}
else $str = $_SESSION['var1']; // get the value back from session
?>
Also on the logout time, instead of deleting the whole session global variable, you should delete the specific session.
session_unset($_SESSION['specific_session']);

PHP: Can't Set Cookie

For some reason, I can't seem to set a cookie in one of my PHP files. All of the code works fine, except it refuses to set the cookie. I've placed different versions of cookie setting with different arguments, but it doesn't seem to make a difference. On top of that, I can set a cookie using that same line of code in a separate PHP file in the same directory. I've tried placing setcookie() at different places and I still get the same result. Am I missing something?
<?php
$table_name="lfgs";
$name=$_POST['name'];
$event="[";
$level=$_POST['level'];
$comments=$_POST['comments'];
$hours=$_POST['hours']*60*60;
$minutes=$_POST['minutes']*60;
$time=$hours+$minutes+time();
setcookie("remember", $name, $time, 'www.domain.com', '/');
if(isset($_POST['event'])){
if (is_array($_POST['event'])) {
foreach($_POST['event'] as $value){
$event = $event . "\"" . $value . "\",";
}
} else {
$value = $_POST['event'];
$event = $event . "\"" . $value . "\"]";
}
} else {
$event = "";
}
if($event[strlen($event)-1] == ',') {
$event = substr_replace($event ,"]",-1);
}
$con=mysqli_connect("domain.com","username","password","database");
$req="INSERT INTO $table_name(name, event, level, comments, time) VALUES ('$name', '$event', '$level', '$comments', '$time')";
mysqli_query($con,$req);
mysqli_close($con);
foreach($_COOKIE as $c) {
echo $c . "<br />";
}
?>
Edit: This is ALL the code for the entire file.
According to the php reference, the correct way to use the setcookie function is
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Didn't you swaped the $path and $domain argument?
Try
setcookie("remember", $name, $time, '/', 'www.domain.com');
try
setcookie("remember", $name, '/', $time);
I dont't understand what you want to do, but it'll not works the way you do.
Always remember: you work with PHP on the server side.
So to set a cookie an then to test if it worked, you need always tow steps (because you are on the server side):
The first step is to set the cookie.
And then during the next request you can check if ur cookie contains in the global $_COOKIE array. if yes then ok, if not then mybe the client/user donsen't allow to set cookies.
If you need to do it in "one step", you should use JavaScript. Something like that:
On submit the form, set the cookie and then propagate the submit action (send the data to the server). JQuery support a good solution to set and read cookies.
Are you sure the php interpreter doesn't send a char before the setcookie() call for some reason? The function send a HTTP header, so it have to appear before any printing on the page.
From my experience, if you have any session active on the page it will not allow you to create PHP cookies. Start a new blank page and test it that way.
You should be able to set a cookie on the new generic page. Then go back to your other page that has a session started on it. Echo the details of that set cookie in the session page and you will get the stored value, no problem.
You can call cookies but you can't seem to create them in an active session page. At least, I can't with my current system settings/config.

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];

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