Set cookie and then refresh page, PHP - php

I'm sure this topic had been addressed before, but I can't seem to find an adequate solution to my problem, which I'm sure is not unique.
So I get that you can't set a cookie and expect to use without refreshing the page. So I'm wondering what my options are.
I have a simple set of links that change the language on the page by setting a cookie to that user's language preference. I need to detect that cookie to assign a variable so that I can then change the page output to the designated language.
So, when the button is pressed, it sends a get variable to the URL bar, which then sets the cookie. After I refresh the page, I get what I want.
Basically, I need to pass the GET variable and then refresh the page. How can I do this?
my php code:
// if someone is trying to change the language
if(isset($_GET['lang']))
{
// change the cookie value to that language
$value = $_GET['lang'];
}
// elseif they are not trying to change the language, and a cookie is already set
elseif(isset($_COOKIE['language_pref']))
{
// maintain the value of the language set in the cookie
$value = $_COOKIE['language_pref'];
}
// if get nor cookie is set
else
{
// set default language to english
$value = 'en_US';
}
$name = 'language_pref';
// cookie expires in 2 years
$expireDate = time() + (2 * 365 * 24 * 60 * 60);
$path = '/';
$domain = 'example.com';
$secure = false; //only transmit the cookie if a HTTPS connection is established
$httponly = true; //make cookie available only for the HTTP protocol (and not for JavaScript)
setcookie( $name, $value, $expireDate, $path, $domain, $secure, $httponly);
My HTML:
ZH
EN

Ok so here is what your page looks like:
> Read cookie and get the language
> Read GET variable and SET COOKIE
> Print out stuff in their language
You are simply doing things in the wrong order. If you do things in this order:
> Read GET variable and SET COOKIE
> Read cookie and get the language
> Print out stuff in their language
You'll already have the right language and have no need to refresh the page.

I think all you are missing is the button that links to the url that contains this php.
If your button however you have implemented it has a href containing the url to this page, then when you click on it, you will have refreshed the page and read the contents of the cookie into $value.
try closing the php tags and then adding :
<a href='PAGE_URL_HERE'>button</a>

You could use a php header or JavaScript included in the else component of your code that only gets executed if the statement meets all of your conditions because all you want is to refresh the page after the cookie is set and or read

cleared it up with this php, which allows me to translate the current page according to the get variable and all later pages with the stored cookie
if(isset($value))
{
$language = $value;
}
else
{
$language = $_COOKIE['language_pref'];
}

Related

How to change Cookies value at runtime [duplicate]

I have the following PHP function:
function validateUser($username){
session_regenerate_id ();
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
setcookie('username2',$username,time()+60*60*24*365);
header("Location: ../new.php");
}
And then I fetch the cookie:
echo $_COOKIE['username2']; exit();
(I only put exit() for debugging purposes)
Only problem, it's coming out blank. Any ideas?
UPDATE:
This is how the function is called:
if(mysql_num_rows($queryreg) != 0){
$row = mysql_fetch_array($queryreg,MYSQL_ASSOC);
$hash = hash('sha256', $row['salt'] . hash('sha256', $password));
if($hash == $row['password']) {
if($row['confirm'] == 1){
if(isset($remember)){
setcookie('username',$username,time()+60*60*24*365);
setcookie('password',$password,time()+60*60*24*365);
} else {
setcookie('username','',time()-3600);
setcookie('password','',time()-3600);
}
validateUser($username);
I didn't include all the if() statements to save some space.
try adding the path = /, so that the cookie works for the whole site not just the current directory (that has caught me out before)
example
setcookie('password',$password,time()+60*60*24*365, '/');
also make sure the cookie is the first thing being output
as advised in the php manual (this has caught me out before too)
Like other headers, cookies must be sent before any output from your
script (this is a protocol restriction).
Why you are having this problem
The problem comes from the fact that setcookie() doesn't set the cookies immediately, it sends the headers so the browser sets the cookies. This means that, for the current page load, setcookie() will no generate any $_COOKIE.
When the browser later on requests a page, it sends the cookies in the headers so the PHP can retrieve them in the form of $_COOKIE.
Simple, old solution
About solutions, the obvious one:
setcookie('username',$username,time()+60*60*24*365);
// 'Force' the cookie to exists
$_COOKIE['username'] = $username;
A better solution
I created a class, Cookie, that addresses the problems that setcookie() and $_COOKIE share:
// Class that abstracts both the $_COOKIE and setcookie()
class Cookie
{
// The array that stores the cookie
protected $data = array();
// Expiration time from now
protected $expire;
// Domain for the website
protected $domain;
// Default expiration is 28 days (28 * 3600 * 24 = 2419200).
// Parameters:
// $cookie: $_COOKIE variable
// $expire: expiration time for the cookie in seconds
// $domain: domain for the application `example.com`, `test.com`
public function __construct($cookie, $expire = 2419200, $domain = null)
{
// Set up the data of this cookie
$this->data = $cookie;
$this->expire = $expire;
if ($domain)
$this->domain = $domain;
else
{
$this->domain =
isset($_SERVER['HTTP_X_FORWARDED_HOST']) ?
$_SERVER['HTTP_X_FORWARDED_HOST'] :
isset($_SERVER['HTTP_HOST']) ?
$_SERVER['HTTP_HOST'] :
$_SERVER['SERVER_NAME'];
}
}
public function __get($name)
{
return (isset($this->data[$name])) ?
$this->data[$name] :
"";
}
public function __set($name, $value = null)
{
// Check whether the headers are already sent or not
if (headers_sent())
throw new Exception("Can't change cookie " . $name . " after sending headers.");
// Delete the cookie
if (!$value)
{
setcookie($name, null, time() - 10, '/', '.' . $this->domain, false, true);
unset($this->data[$name]);
unset($_COOKIE[$name]);
}
else
{
// Set the actual cookie
setcookie($name, $value, time() + $this->expire, '/', $this->domain, false, true);
$this->data[$name] = $value;
$_COOKIE[$name] = $value;
}
}
}
Then you can use it like this:
$Cookie = new Cookie($_COOKIE);
$User = $Cookie->user;
$LastVisit = $Cookie->last;
$Cookie->last = time();
And of course, you have to pass it around. Much better than having globals.
Here is the general syntax of setcookie
setcookie(name,value,expire,path,domain,secure);
Look at third argument, if you do not set it the script will take it to current working directory. So if you set a cookie without setting path at a.com/b/setcookie.php the cookie will not be available to a.com/checkcookie.php. What you are doing is setting cookie in a subfolder and the redirecting to a parent folder, look at ../, where it is not available hence the issue. How to avoid this? Normal procedure is to supply a path that is /, in your case supply / as fourth param. The fifth argument for your cookie will set it secure. http://www.php.net/setcookie has more explanation. This should fix your problem. Setting domain path to domain.com, will make the cookie available to everything under domain.com but not to something.domain.com. Set domain value to .domain.com, look at the dot preceding domain.com, will make it available across anything.domain.com. HTH!
Thought I would add another possible reason why a cookie may not be either setting or showing random functional behavior.
The following case may be applicable to some programmers having what appears to be an illusive cookie setting issue as a result of the incorrect usage of header_remove()
If you try to set a cookie before calling header_remove(), the cookie will never be created because you have also immediately destroyed the header that was set in order to create the cookie before it was buffered out to the client.
You may find when fiddling around that your cookie suddenly works for an unknown reason, so you need to understand the race-conditions around headers:
On first run you set a cookie and don't call header_remove() at all.
On a second run you do call header_remove()
You will find your cookie is now always set regardless of condition (2) and the number of times it is called because (1) happened first at least once.
The cookie will remain set until it either expires, is overwritten or unset()
The same will apply when modifying headers like a cookie value before the eventual call of header_remove(), you again will fail to set new values because they will be wiped before the response is buffered out to the user.
You need to set cookies and any other headers for that matter after a header_remove() not before.
Use header_remove() to cleanup ALL previously set headers in order to set new headers for a final output.
An example of scenario for such a case may be as follows:
Use header_remove() to alter a hierarchy of HTTP Response codes for a RESTFUL API where you are using axios with interceptors.
Your application sets a 400+ header error first, should the application error out at any point of execution.
Modify the header to a 200 when final desired execution point has been reached & a valid response is expected.
In such an event, it is likely you want to preserve all other previously set headers but clear out the HTTP Status (400?) code in order to set a new (200?) code for the final response.
If you try to set the header again in order to change the status code before removing the previously set header then you will get the "Headers already sent" error.
You can remove specific headers with header_remove, here is how to unset the status code and set a new code in stages:
// Set a default status code
http_response_code(500);
// Boot Logic runs - if fails here 500 is returned
// Authentication Logic - If unauthorized ?
header_remove('HTTP/1.0'); // Clear previous 500
http_response_code(401); // Set new status code
// else ?
// Return Data Logic - Success
header_remove('HTTP/1.0'); // Clear previous 500
http_response_code(200) // Set new status code
This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
this is how the structure looks
<?php
$cookie_name = "user";
$cookie_value = "Ahmed Moftah";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<html>
<body>
</body>
</html>
It might be a cache problem. Try closing the browser and opening a new one with the localhost file path. I had the same issue and my page was cached so the cookies weren't working, even though I could put in new code and see a change on the page. Very weird... Cleaning your cache might help, try that first. Then try a new browser, then try to go to your localhost:8080 index and hit refresh to see when the last page was modified.
If that doesn't fix it, try restarting LAAMP or XAAMP or whatever you are using.
This happens with the session cookies are disabled.
You can navigate to your php.ini file(changes depending on server. Ubuntu 20.04's default is /etc/php/{X.x}/{apache2|[others]}/php.ini) and ensure that session.use_cookies=1
Restart your server and then try to set the cookie. They should immediately be available.
You probably have sent header hereby making it impossible to set header for cookie.
It might be a simple solution of ob_start() at the start of your page.
[Solution tested in XAMPP for PHP 8.0.19]
I modified the file php.ini and set session.auto_start=1. Keep in mind that i'm calling session_set_cookie_params([param => value]) just before session_start() every time this functions appears in my code, in every file.
session.auto_star: Initialize session on request startup.
http://php.net/session.auto-start
Still studying and analysing the reason and functionality of this, it was kind of a serendipity.
Probably not the most secure solution.
You can't get the $_COOKIE on the same request but you can get $_SESSION on the same request.
So the idea is
Set the $username in both the session & cookie.
Get the username from the session for the first time (if the same request)
Unset session
Always get the cookie from $_COOKIE from next request.
// Set Cookie
setcookie('username',$username,time()+60*60*24*365);
$_SESSION['username'] = $username;
//GET Cookies
if(!$_COOKIE['username']){
$username = $_SESSION['username'];
unset($_SESSION['username']);
}else{
$username = $_COOKIE['username'];
}

PHP page keeps refreshing after COOKIE is set

The following code is the first code in my php page.
$current_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(isset($_REQUEST["lang"])){ //check if different language was selected
$lang = $_REQUEST["lang"];
if($lang == "eng"){
$lang_value = 1;
}else{
$lang_value = 0;
}
setCookie('language',$lang);
setCookie('language_value',$lang_value);
header("Refresh:0; url=".$current_link);
}else{ //if different language was not selected, check if cookie is set with language value
if(isset($_COOKIE["language"])){
$lang = $_COOKIE["language"];
$lang_value = $_COOKIE["language_value"];
}else{ //if cookie with language value is not set, create it now with default language option
setCookie('language','eng');
setCookie('language_value',1);
header("Refresh:0; url=".$current_link);
}
}
The visitor can only choose one of two languages. If a language is chosen, cookies with the chosen language values are created.
If a language is not chosen, the script checks if a cookie with the language value exists, and if so, accesses the cookie values. If a cookie with the language value does not exist, cookies with the default language (English) values are created.
The page is suppose to only refresh when cookies are created and continue the rest of the code if the cookie with the language value exists. However, the page keeps on refreshing even after the cookies were created and are accessible. eg:
echo $_COOKIE["language"]; //will output the selected language value
Not sure if there is something wrong with the logic here, but any help will be appreciated.
Thanks
I managed to solve the mystery.
The problem was in the .htaccess file setup, eg:
RewriteRule diploma-golf course.php?lang=eng&courseid=15 [NC])
Since I only saw the 'diploma-golf' part at the end of the url, I never realised that the "lang" value was passed on every time the page refreshed. So because the script received the "lang" value each time, it created a new cookie each time, resulting in the infinite refreshing. Changed the if statement logic and now everything is working as it should.
Every request to the page will run this part:
if(isset($_REQUEST["lang"])){
That means that the page will be refreshed because of this unconditional part of your code:
header("Refresh:0; url=".$current_link);
What you might want to do is removing the first Header part and only keep the header part as described in your text.
It would look like so:
$current_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(isset($_REQUEST["lang"])){ //check if different language was selected
$lang = $_REQUEST["lang"];
if($lang == "eng"){
$lang_value = 1;
}else{
$lang_value = 0;
}
setCookie('language',$lang);
setCookie('language_value',$lang_value);
#header("Refresh:0; url=".$current_link); ### Removing this line
}else{ //if different language was not selected, check if cookie is set with language value
if(isset($_COOKIE["language"])){
$lang = $_COOKIE["language"];
$lang_value = $_COOKIE["language_value"];
}else{ //if cookie with language value is not set, create it now with default language option
setCookie('language','eng');
setCookie('language_value',1);
header("Refresh:0; url=".$current_link);
}
}
You need to add expire and path for the cookie:
setCookie('language',$lang, time() + (86400 * 30), "/"); // 86400 = 1 day

New cookie value not taken into account without refreshing page [duplicate]

I have the following PHP function:
function validateUser($username){
session_regenerate_id ();
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
setcookie('username2',$username,time()+60*60*24*365);
header("Location: ../new.php");
}
And then I fetch the cookie:
echo $_COOKIE['username2']; exit();
(I only put exit() for debugging purposes)
Only problem, it's coming out blank. Any ideas?
UPDATE:
This is how the function is called:
if(mysql_num_rows($queryreg) != 0){
$row = mysql_fetch_array($queryreg,MYSQL_ASSOC);
$hash = hash('sha256', $row['salt'] . hash('sha256', $password));
if($hash == $row['password']) {
if($row['confirm'] == 1){
if(isset($remember)){
setcookie('username',$username,time()+60*60*24*365);
setcookie('password',$password,time()+60*60*24*365);
} else {
setcookie('username','',time()-3600);
setcookie('password','',time()-3600);
}
validateUser($username);
I didn't include all the if() statements to save some space.
try adding the path = /, so that the cookie works for the whole site not just the current directory (that has caught me out before)
example
setcookie('password',$password,time()+60*60*24*365, '/');
also make sure the cookie is the first thing being output
as advised in the php manual (this has caught me out before too)
Like other headers, cookies must be sent before any output from your
script (this is a protocol restriction).
Why you are having this problem
The problem comes from the fact that setcookie() doesn't set the cookies immediately, it sends the headers so the browser sets the cookies. This means that, for the current page load, setcookie() will no generate any $_COOKIE.
When the browser later on requests a page, it sends the cookies in the headers so the PHP can retrieve them in the form of $_COOKIE.
Simple, old solution
About solutions, the obvious one:
setcookie('username',$username,time()+60*60*24*365);
// 'Force' the cookie to exists
$_COOKIE['username'] = $username;
A better solution
I created a class, Cookie, that addresses the problems that setcookie() and $_COOKIE share:
// Class that abstracts both the $_COOKIE and setcookie()
class Cookie
{
// The array that stores the cookie
protected $data = array();
// Expiration time from now
protected $expire;
// Domain for the website
protected $domain;
// Default expiration is 28 days (28 * 3600 * 24 = 2419200).
// Parameters:
// $cookie: $_COOKIE variable
// $expire: expiration time for the cookie in seconds
// $domain: domain for the application `example.com`, `test.com`
public function __construct($cookie, $expire = 2419200, $domain = null)
{
// Set up the data of this cookie
$this->data = $cookie;
$this->expire = $expire;
if ($domain)
$this->domain = $domain;
else
{
$this->domain =
isset($_SERVER['HTTP_X_FORWARDED_HOST']) ?
$_SERVER['HTTP_X_FORWARDED_HOST'] :
isset($_SERVER['HTTP_HOST']) ?
$_SERVER['HTTP_HOST'] :
$_SERVER['SERVER_NAME'];
}
}
public function __get($name)
{
return (isset($this->data[$name])) ?
$this->data[$name] :
"";
}
public function __set($name, $value = null)
{
// Check whether the headers are already sent or not
if (headers_sent())
throw new Exception("Can't change cookie " . $name . " after sending headers.");
// Delete the cookie
if (!$value)
{
setcookie($name, null, time() - 10, '/', '.' . $this->domain, false, true);
unset($this->data[$name]);
unset($_COOKIE[$name]);
}
else
{
// Set the actual cookie
setcookie($name, $value, time() + $this->expire, '/', $this->domain, false, true);
$this->data[$name] = $value;
$_COOKIE[$name] = $value;
}
}
}
Then you can use it like this:
$Cookie = new Cookie($_COOKIE);
$User = $Cookie->user;
$LastVisit = $Cookie->last;
$Cookie->last = time();
And of course, you have to pass it around. Much better than having globals.
Here is the general syntax of setcookie
setcookie(name,value,expire,path,domain,secure);
Look at third argument, if you do not set it the script will take it to current working directory. So if you set a cookie without setting path at a.com/b/setcookie.php the cookie will not be available to a.com/checkcookie.php. What you are doing is setting cookie in a subfolder and the redirecting to a parent folder, look at ../, where it is not available hence the issue. How to avoid this? Normal procedure is to supply a path that is /, in your case supply / as fourth param. The fifth argument for your cookie will set it secure. http://www.php.net/setcookie has more explanation. This should fix your problem. Setting domain path to domain.com, will make the cookie available to everything under domain.com but not to something.domain.com. Set domain value to .domain.com, look at the dot preceding domain.com, will make it available across anything.domain.com. HTH!
Thought I would add another possible reason why a cookie may not be either setting or showing random functional behavior.
The following case may be applicable to some programmers having what appears to be an illusive cookie setting issue as a result of the incorrect usage of header_remove()
If you try to set a cookie before calling header_remove(), the cookie will never be created because you have also immediately destroyed the header that was set in order to create the cookie before it was buffered out to the client.
You may find when fiddling around that your cookie suddenly works for an unknown reason, so you need to understand the race-conditions around headers:
On first run you set a cookie and don't call header_remove() at all.
On a second run you do call header_remove()
You will find your cookie is now always set regardless of condition (2) and the number of times it is called because (1) happened first at least once.
The cookie will remain set until it either expires, is overwritten or unset()
The same will apply when modifying headers like a cookie value before the eventual call of header_remove(), you again will fail to set new values because they will be wiped before the response is buffered out to the user.
You need to set cookies and any other headers for that matter after a header_remove() not before.
Use header_remove() to cleanup ALL previously set headers in order to set new headers for a final output.
An example of scenario for such a case may be as follows:
Use header_remove() to alter a hierarchy of HTTP Response codes for a RESTFUL API where you are using axios with interceptors.
Your application sets a 400+ header error first, should the application error out at any point of execution.
Modify the header to a 200 when final desired execution point has been reached & a valid response is expected.
In such an event, it is likely you want to preserve all other previously set headers but clear out the HTTP Status (400?) code in order to set a new (200?) code for the final response.
If you try to set the header again in order to change the status code before removing the previously set header then you will get the "Headers already sent" error.
You can remove specific headers with header_remove, here is how to unset the status code and set a new code in stages:
// Set a default status code
http_response_code(500);
// Boot Logic runs - if fails here 500 is returned
// Authentication Logic - If unauthorized ?
header_remove('HTTP/1.0'); // Clear previous 500
http_response_code(401); // Set new status code
// else ?
// Return Data Logic - Success
header_remove('HTTP/1.0'); // Clear previous 500
http_response_code(200) // Set new status code
This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
this is how the structure looks
<?php
$cookie_name = "user";
$cookie_value = "Ahmed Moftah";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<html>
<body>
</body>
</html>
It might be a cache problem. Try closing the browser and opening a new one with the localhost file path. I had the same issue and my page was cached so the cookies weren't working, even though I could put in new code and see a change on the page. Very weird... Cleaning your cache might help, try that first. Then try a new browser, then try to go to your localhost:8080 index and hit refresh to see when the last page was modified.
If that doesn't fix it, try restarting LAAMP or XAAMP or whatever you are using.
This happens with the session cookies are disabled.
You can navigate to your php.ini file(changes depending on server. Ubuntu 20.04's default is /etc/php/{X.x}/{apache2|[others]}/php.ini) and ensure that session.use_cookies=1
Restart your server and then try to set the cookie. They should immediately be available.
You probably have sent header hereby making it impossible to set header for cookie.
It might be a simple solution of ob_start() at the start of your page.
[Solution tested in XAMPP for PHP 8.0.19]
I modified the file php.ini and set session.auto_start=1. Keep in mind that i'm calling session_set_cookie_params([param => value]) just before session_start() every time this functions appears in my code, in every file.
session.auto_star: Initialize session on request startup.
http://php.net/session.auto-start
Still studying and analysing the reason and functionality of this, it was kind of a serendipity.
Probably not the most secure solution.
You can't get the $_COOKIE on the same request but you can get $_SESSION on the same request.
So the idea is
Set the $username in both the session & cookie.
Get the username from the session for the first time (if the same request)
Unset session
Always get the cookie from $_COOKIE from next request.
// Set Cookie
setcookie('username',$username,time()+60*60*24*365);
$_SESSION['username'] = $username;
//GET Cookies
if(!$_COOKIE['username']){
$username = $_SESSION['username'];
unset($_SESSION['username']);
}else{
$username = $_COOKIE['username'];
}

"Session" tracking seems broken

I have Facebook ads that bring users to a website. Each ad has a different tracking ID:
www.scaredycut.com/index.php?azn=TRACKING_ID
Once on the site, the tracking ID is inserted into the link to Amazon (so as to indicate a referral sale if something is bought). If a user comes to the site directly (not through an ad), they receive the tracking ID scaredycut-direct.
I set up two lines of defense: first, a cookie is created that contains TRACKING_ID. In case cookies are disabled, the url tag is still there (azn=TRACKING_ID), up for grabs.
In index.php, an initial php file that redirects to the home page:
# capture TRACKING_ID from URL
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parsed_url = parse_url($actual_link);
$azn = substr($parsed_url[query], 4);
# save tag into a cookie set to expire in 30 days
setcookie ("ScaredyCut_AmazonReferral1", $azn,time()+60*60*24*30);
In the Wordpress' functions.php:
# create TRACKING_ID variable from url tag
$urltrackingID = $_GET["azn"];
# create TRACKING_ID variable from cookie
$cookietrackingID = $_COOKIE["ScaredyCut_AmazonReferral1"];
# logic: which variable to use?
if ($cookietrackingID == NULL) { // if there's no cookie,
if ($urltrackingID == NULL) { // if they came directly,
$trackingID = "scaredycut-direct"; // use tracking ID "scaredycut-direct"
} else { // otherwise, cookies are disabled, so use url tracking ID
$trackingID = $urltrackingID;
}
} else { // otherwise, cookie are enabled, so use cookie tracking ID
$trackingID = $cookietrackingID;
}
In header.php:
# declare global tracking ID var
<?php
global $trackingID;
?>
And then, I just insert $trackingID into the link's href. (I give precedence to cookies. If they have cookies on, I'd rather make a cookie in case they leave and come back later.)
My method is working, for the most part (surprising for the novice I am). Sessions are being tracked correctly, but I have a very strong suspicion that some sessions are being mistakenly tracked as "scaredycut-direct" instead of their ad-specific tracking ID.
The site is, for the most part, a single page. There isn't really a way for a user to lose a url tag by navigating to another page.
Is there a way that sessions are being marked incorrectly as "scaredycut-direct", and bypassing the cookie AND the url tag methods? Is there another way to do this?
Thanks so much for the help.
A third option to add is $_SERVER['HTTP_REFERER'], but it's set by the browser and isn't reliable. It also means that if they come from google, it'll be set to google.
Other than that, it looks okay.

Set cookie and update cookie problem - Php

In an attempt to get more familiar with cookies I've decided to set up a simple cookie management system to have more control of the information that I can store and retrieve from a user.
The idea is to set a cookie if it does not exist, and update a cookie if it already exists on the user.
Once the cookie is set, it will also be stored in a database that will keep track on when the session started and when it was last accessed.
Creating a cookie worked well at first. But suddenly it stopped working and wouldn't set anything at all. This is the current code of the createSession() function:
function createSession() {
// check to see if cookie exists
if(isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test","$cookiekey",$expire,"/",false,0);
} else {
// assign unique cookie id
list($msec,$sec)=explode(" ",microtime());
$cookiekey = preg_replace("/./","",($msec+$sec));
// set time
$expire = time()+81400;
// set cookie
setcookie("test","$cookiekey",$expire,"/",false,0);
// assign the unqiue id to $_COOKIE[]
$_COOKIE["test"]=$cookiekey;
unset($cookiekey);unset($msec);unset($sec);unset($expire);
}
}
Is my approach heading in the right direction or have I done something way wrong?
Doing $_COOKIE["test"] = something; doesn't make a "test" cookie. You need to use setcookie again.
I don't know why you'd want to do that though. Why not just check for $_COOKIE["name"] (the cookie that you are making).
Cookies are only available once another request was done. So don’t modify $_COOKIE on your own.
Furthermore, when in your case the cookie exists (i.e. $_COOKIE['test'] is set) you call setcookie again with $cookiekey as its value. But $cookiekey is not defined at that moment so the cookie will be overwritten with an empty string. I guess you want to use $_COOKIE['test'] instead:
if (isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test", $_COOKIE["test"], $expire, "/", false, 0);
}
You could also save yourself all that pain by using PHP's built in session management (examples here) to handle all of this cookie stuff for you.

Categories