Cookie Not Grabbing All Codes - php

On Page Variable =
$lgc_code = '1,2,3,15,23,30';
Cookie = 'lgc_cntl'
My cookie is housing logic codes for each user to determine what banners or icons should show based on previous web pages visited. I have written the following function:
$lgc=$lgc_code;
// check for variable for multiple codes
$expEncArr = explode(",", $lgc);
$results = count($expEncArr);
if(isset($_COOKIE['lgc_cntl'])) {
// read cookie
$cookie_codes = $_COOKIE['lgc_cntl'];
// Build Array of cookie codes
$expEncArr2 = explode(",", $cookie_codes);
foreach($expEncArr as $l_code) {
if(in_array($l_code, $expEncArr2)) {
$lgc_codes=$_COOKIE['lgc_cntl'];
} else {
$lgc_codes=$_COOKIE['lgc_cntl'].','.$l_code;
} // end array search statement
// add campaign to cookie
setcookie('lgc_cntl',$lgc_codes,time() + (86400 * 365), "/", ".oru.edu"); // 86400 = 1 day
} // end foreach statement
} else {
$lgc_codes = $lgc;
// add campaign to cookie
setcookie('lgc_cntl',$lgc_codes,time() + (86400 * 365), "/", ".oru.edu"); // 86400 = 1 day
} // end isset(cookie) if / else statement
If there is no cookie set, the function works perfectly but if there is a cookie found it only adds the last variable in the array versus any codes not found in the cookie already.
The function should work as follows:
Separate on-page variable into an array
Check for the cookie
Separate Cookie values into an array
Compare the variables on page to values in cookie
Add any on page variables not found in the cookie
It is working all the way through but when the cookie is set, it is only adding the last variable in the string even if none of the others are not located in the cookie array. What am I doing wrong or how can I solve this?

This is a common mistake - $_COOKIE is not affected by calling setcookie. This is because $_COOKIE is created at the beginning of the PHP script execution based on data sent from the browser, and setcookie sends data to the browser.
Consequently, each time you run this line:
$lgc_codes=$_COOKIE['lgc_cntl'].','.$l_code;
Your value of $lgc_codes is the cookie string originally sent by the browser plus exactly one extra code.
The solution is to instead use a local variable, such as $new_cookie_value, to build up the full string, and then call setcookie once:
$new_cookie_value = $_COOKIE['lgc_cntl'];
foreach($expEncArr as $l_code) {
// if statement removed to keep example brief
// Add extra code to list
$new_cookie_value = $new_cookie_value .','.$l_code;
}
// Now call setcookie once with the desired value
setcookie('lgc_cntl',$new_cookie_value,time() + (86400 * 365), "/", ".oru.edu");
[Aside: Do not underestimate the value of good variable names. Your code would be much clearer if $expEncArr and $expEncArr2 had longer names which described what the difference was between them. Similarly, $lgc, $lgc_code, $lgc_codes, etc.]

Your logic is very muddled. This is what should be in the first portion of your if block
// read cookie
$cookie_codes = $_COOKIE['lgc_cntl'];
// Build Array of cookie codes
$expEncArr2 = explode(",", $cookie_codes);
$lgc_codes = $_COOKIE['lgc_cntl'];
foreach ($expEncArr as $l_code)
{
if (!in_array($l_code, $expEncArr2))
{
$lgc_codes .= ',' . $l_code;
}
}
setcookie('lgc_cntl', $lgc_codes, time() + (86400 * 365), "/", ".oru.edu");

Related

How to get the latest cookie id without additional page reloading?

There is a page, that can be visited with one of three params: ref1, ref2 and ref3. Each time page script sets a couple of cookies to store ref-param and time of it's creation. After that it should find the latest one and be ready to deal with it.
For example if I have "ref1" cookie as latest before visiting page and visit
script.php?ref2=1
it should echo
latest is ref2
But it works properly (echoes right latest cookie) only after additional reloading of the page. What's wrong with this code?
if ($_GET['ref1']) {
setcookie('ref1', 'ref1');
setcookie('ref1_dt', time());
}
if ($_GET['ref2']) {
setcookie('ref2', 'ref2');
setcookie('ref2_dt', time());
}
if ($_GET['ref3']) {
setcookie('ref3', 'ref3');
setcookie('ref3_dt', time());
}
function getLatestCookie() {
$refs = array(
'ref1' => $_COOKIE['ref1_dt'],
'ref2' => $_COOKIE['ref2_dt'],
'ref3' => $_COOKIE['ref3_dt']
);
$maxs = array_keys($refs, max($refs));
return $maxs[0];
}
$latest = getLatestCookie();
setcookie('latest', $latest, time() + 60 * 60 * 24 * 30, "/");
echo "latest is " . $latest;
As usual, reading docs was good enough.
Cookies are available in $_COOKIE array after next page loading. So in my case I should assign $latest to GET-param value if it exists and else assign it with getLatestCookie().

Unset cookies on all pages [duplicate]

I need to figure out how to unset this cookie. Everything I tried so far has failed.
This is how I am currently unsetting it and it doesn't seem to work.
setcookie("user_id", $user_id, time() - 7200);
This is how I set it:
setcookie("user_id", $user_id, time() + 7200);
I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.
The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.
The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.
function set_session_from_cookie()
{
if (isset($_SESSION['user_id'])) {
echo '';
} else {
$_SESSION['user_id']=$_COOKIE['user_id'];
}
}
Logout:
<?php
require'core.php';
session_destroy();
setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');
I set my cookie with the following code:
if ($rememberme == "on") {
$user_id = mysql_result($query_run, 0, 'id');
setcookie("user_id", $user_id, time() + 7200);
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
} else {
if ($rememberme == "") {
echo 'ok';
$user_id = mysql_result($query_run, 0, 'id');
echo $user_id;
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
}
}
How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.
Set the cookie's expiration date to a time in the past (like one second after epoch, for example).
setcookie("yourCookie", "yourValue", 1);
This will cause the cookie to expire.
1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.
The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.
I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:
setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");
The last parameter is the path. And it worked.
My original setcookie looks like this:
setcookie("user_id", $user_id, time() + 7200, "");
There are few security concerns regarding you code, however to answer your question, to unset a cookie in php, all you need to do is to set expiration time to a time in the past:
setcookie("user_id", "", time()-10, "/");
"loginform.php" is not a valid domain, that might be the problem here.
Look at the php manual for information on setcookie
http://php.net/manual/en/function.setcookie.php
These notes should explain the process:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies must be deleted with the same parameters as they were set
with. If the value argument is an empty string, or FALSE, and all
other arguments match a previous call to setcookie, then the cookie
with the specified name will be deleted from the remote client. This
is internally achieved by setting value to 'deleted' and expiration
time to one year in past.
Because setting a cookie with a value of FALSE will try to delete the
cookie, you should not use boolean values. Instead, use 0 for FALSE
and 1 for TRUE.
use this code
setcookie("CookieName", "", time()-(60*60*24), "/");
works everytime for me in every website
In php manual, you can delete a cookie by setting a expiration date is in the past:
setcookie("key","",time()-3600);
In some case, you should provide path and domain for arguments.
In fact, if you assign a cookie with a empty string, it'll also be unset:
setcookie("key","");

how to unset cookie in PHP?

I need to figure out how to unset this cookie. Everything I tried so far has failed.
This is how I am currently unsetting it and it doesn't seem to work.
setcookie("user_id", $user_id, time() - 7200);
This is how I set it:
setcookie("user_id", $user_id, time() + 7200);
I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.
The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.
The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.
function set_session_from_cookie()
{
if (isset($_SESSION['user_id'])) {
echo '';
} else {
$_SESSION['user_id']=$_COOKIE['user_id'];
}
}
Logout:
<?php
require'core.php';
session_destroy();
setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');
I set my cookie with the following code:
if ($rememberme == "on") {
$user_id = mysql_result($query_run, 0, 'id');
setcookie("user_id", $user_id, time() + 7200);
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
} else {
if ($rememberme == "") {
echo 'ok';
$user_id = mysql_result($query_run, 0, 'id');
echo $user_id;
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
}
}
How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.
Set the cookie's expiration date to a time in the past (like one second after epoch, for example).
setcookie("yourCookie", "yourValue", 1);
This will cause the cookie to expire.
1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.
The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.
I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:
setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");
The last parameter is the path. And it worked.
My original setcookie looks like this:
setcookie("user_id", $user_id, time() + 7200, "");
There are few security concerns regarding you code, however to answer your question, to unset a cookie in php, all you need to do is to set expiration time to a time in the past:
setcookie("user_id", "", time()-10, "/");
"loginform.php" is not a valid domain, that might be the problem here.
Look at the php manual for information on setcookie
http://php.net/manual/en/function.setcookie.php
These notes should explain the process:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies must be deleted with the same parameters as they were set
with. If the value argument is an empty string, or FALSE, and all
other arguments match a previous call to setcookie, then the cookie
with the specified name will be deleted from the remote client. This
is internally achieved by setting value to 'deleted' and expiration
time to one year in past.
Because setting a cookie with a value of FALSE will try to delete the
cookie, you should not use boolean values. Instead, use 0 for FALSE
and 1 for TRUE.
use this code
setcookie("CookieName", "", time()-(60*60*24), "/");
works everytime for me in every website
In php manual, you can delete a cookie by setting a expiration date is in the past:
setcookie("key","",time()-3600);
In some case, you should provide path and domain for arguments.
In fact, if you assign a cookie with a empty string, it'll also be unset:
setcookie("key","");

Trying to read someone's code re cookies

I am trying to read some code here (not my own) and make changes. So far what I can get from reading it is that if a variable named $cuid is NOT set, it sends a user to a splash page. If it IS set, it sets the cookie to the $cuid variable (which is actually not happening, the cookie isn't updated when you come with a new CUID in GET)
Here's the code:
if (!$cuid || $reset)
{
$cuid="";
if( $cuid_demo!="samplecu" && $cuid!="75541953" )
setcookie("cuid","",time() - 31536000); //DELETES COOKIE
$query="UPDATE cusucceed SET kkc_visits=kkc_visits+1 WHERE id = '$cuid'";
$result=dbquery($link, $query) or die("error: ".dberror() );
include("splash.php");
}
else
{
setcookie("cuid","",time() - 31536000); //DELETES COOKIE
setcookie("cuid",$cuid,time()+604800); //1 week.
select_db($link) or die("error: ".dberror() );
if($admin_id)
{
$cuid=$cuid;
$id=$cuid;
}
$query="UPDATE cusucceed SET kkc_visits=kkc_visits+1 WHERE id = '$cuid'";
$result=dbquery($link, $query)or die("Database Server Error 2");
include("index_main.php");
Am I reading that correctly? The else part of the if statement should be setting the cuid cookie to $cuid, if $cuid is set, yes?
If $cuid is unassigned (more explicity, has a false result [albeit 0, false, empty]) or it should be $reset,
- Force-empty the cookie (assuming it's not [what appears to be] a test account)
- Display the splash page.
If $cuid is set (and it's not a $reset),
- Re-declare the cuid cookie, and make it last for a week. Then also display the main page.
In both instances,
- Increment the number of times the found $cuid has visited the page.
Although to be honest, it looks like the author wasn't really sure what they were doing based on duplicated code and that they feel the need to empty a cookie before re-declaring it.

How to get cookie's expire time

When I create a cookie, how to get cookie's expire time?
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie.
Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
When you create a cookie via PHP die Default Value is 0, from the manual:
If set to 0, or omitted, the cookie
will expire at the end of the session
(when the browser closes)
Otherwise you can set the cookies lifetime in seconds as the third parameter:
http://www.php.net/manual/en/function.setcookie.php
But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).
It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:
Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain
This way you can also get deleted ones since their value is deleted:
Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain
From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.
This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.
For more info see:
https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php
To get cookies expire time, use this simple method.
<?php
//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;
//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);
//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){
return ($sec / 60 / 60 / 24);
}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){
echo "Cookie is set<br />";
if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
echo "Cookie will expire today.";
}else{
echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
}
}else{
echo "not set...";
}
?>
You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

Categories