Jump to content

Cookie Headache


jarvis

Recommended Posts

Hi All,

 

I seem to be getting in a right mess with this, so hope someone can help.

 

I'm simply trying to set a cookie called 'defaultLanguage'.

 

It will initially be set to English and when someone completes a form, the form value is then passed and used in the cookie.

 

here's my code:

$cookie_name = 'defaultLanguage';
$cookie_value = $_GET["language"];
if ($cookie_value == ''){
	$cookie_value = 'English';
}else{
	$cookie_value = $_GET["language"];
}
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day

I then use this to test/check:

$cookie_name = 'defaultLanguage';
if(!isset($_COOKIE[$cookie_name])) {
  print 'Cookie with name "' . $cookie_name . '" does not exist...';
} else {
  print 'Cookie with name "' . $cookie_name . '" value is: ' . $_COOKIE[$cookie_name];
}

If I clear my browser cookies, this is what happens:

  1. On initial page load it says: Cookie with name "defaultLanguage" does not exist...
  2. If I reload the page or move to another, it says: Cookie with name "defaultLanguage" value is: English
  3. If I then complete my form, ?language=French is added to the URL, however, it still says: Cookie with name "defaultLanguage" value is: English

I think I' missing something obvious but can't see for looking!!

 

Any help is much appreciated

Link to comment
Share on other sites

The values of cookies are not updated until the next page request/reload. This is because cookies are sent to and from the client during HTTP requests.

 

After step 3 if you reload the page, the $_COOKIE['defaultLanguage'] should reflect the new value of the chosen language made by the user. 

 

An alternative to cookies is (server-side) sessions. Any changes made to sessions will be immediate, only difference is the session data is stored server side rather than client side.

Link to comment
Share on other sites

Hi Jarvis,

 

I am still new with cookies / sessions and all so this may not work, but could you try this:

$cookie_name = 'defaultLanguage';

if (empty($cookie_value)){
	
	$cookie_value = 'English';
	setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
	
}else{

	$cookie_value = $_GET["language"];
	setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day

}
Link to comment
Share on other sites

Thanks Ansego but still no joy. I wonder if it's because I'm using Wordpress but this should make no difference as it's included within the header file

 

Ginerjm, are you referring to domain and secure? If so, I thought they were optional so no need to include them

Link to comment
Share on other sites

Further reading of the manual indicates that while the sample header of the function call implies that the domain is not optional, the text below indicates that it may be left out. As for the path, I failed to see that you did include that one. So - ignore my response.

 

As already mentioned above, be sure that no output precedes your call to setcookie AND also realize that you won't see an updated cookie value until the next page load. That means if you set the cookie in your script and want to check it immediately after, you can't. So if you are using user input to set the cookie, use that same input to set a local var to be used during the rest of the script. Do the same when retrieving the cookie value on successive executions.

Link to comment
Share on other sites

Sorry bit like blind leading blind, I just got over my head ache with sessions.

 

Did not see anything check if $_COOKIE["defaultLanguage"] pre existed.

 

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie. From: http://www.php.net/manual/en/function.setcookie.php

 

In regards to @ ginerjm

 

 

Have a look at the manual re: setcookie. To me it appears you are leaving off 2 parameters that PHP does not default for you.

 

Manual: http://www.php.net/manual/en/function.setcookie.php

 

ginerjm: You talking about example #1 OR Path, Domain, Secure and httponly? 

 

Example #1:

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

Test Example:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?> 
Link to comment
Share on other sites

the logic setting the cookie to a default of English is ran unconditionally, so any time you visit the page where the setcookie() code is at, it will set the cookie using whatever $_GET['language'] is, even it if there's no $_GET['language'] on the end of the url.

 

you should actually only set the cookie when $_GET['language'] is not empty and use the absence of the cookie to default to English.

Link to comment
Share on other sites

Thanks Ansego.

 

OK, I now have:

if (isset($_GET['language'])){
	setcookie ('defaultLanguage', $_GET['set'], time()+(86400 * 30), '/', 'localhost', '0'); // 86400 = 1 day
	$set_language = $_GET['language'];
}elseif (isset($_COOKIE['defaultLanguage'])) {
	$set_language=$_COOKIE['defaultLanguage'];
} else {
	setcookie ('defaultLanguage', 'English', time()+(86400 * 30), '/', 'localhost', '0');
	$set_language = 'English';
}

If I then do:

echo $set_language;

It shows English, it then shows the language I want as soon as I submit the form. However, once I then navigate off of the page, it reverts back to English.

 

Not sure if this is progress or not Lol

Link to comment
Share on other sites

Thanks @mac_gyver

 

If I've understood you, you mean:

$cookie_name = 'defaultLanguage';
$cookie_value = $_GET["language"];
if ($cookie_value != ''){	
	$cookie_value = $_GET["language"];
	setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
}else{
	$cookie_value = 'English';
	setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
}

Sadly that doesn't work either (assuming I've interpreted what you meant!?)

Link to comment
Share on other sites

lol @jarvis

 

mac_gyver and Ch0cu3r suggestion is to redirect off that page for the result as it does not change it there and then. I had similar problems with sessions too and had to redirect it.

 

I think there is a rule that this is meant to be at the top of the page but I've used it with in the page: header( 'Location: index.php' ) ;  for redirection.

 

Maybe try:

	$cookie_name = 'defaultLanguage';
	
	if (isset($_GET["language"]) && !empty($_GET["language"])){

		$cookie_value = $_GET["language"];
		setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
		header( 'Location: index.php' ); // Redirect to a page
	
	}else{
		
		$cookie_value = 'English';
		setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); // 86400 = 1 day
		header( 'Location: index.php' ); // Redirect to a page

	}

If this does not work hopefully these guru's can shed some more light. But least this will have a redirection, just hope the logic is right.

 

Good luck ;-)

Link to comment
Share on other sites

code to set the cookie -

$cookie_name = 'defaultLanguage';

// set cookie only when the url contains a value
if(isset($_GET['language'])){
    // note: you should validate $_GET['language'] to insure it contains exactly only one of the permitted values before using it at all
    setcookie($cookie_name, $_GET['language'], time() + (86400 * 30), '/');
}

code to get the cookie value -

$cookie_name = 'defaultLanguage';
// get cookie value or a default
$cookie_value = isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : 'English';
// note: you should validate $cookie_value to insure it contains exactly only one of the permitted values before using it at all
Link to comment
Share on other sites

Sorry to add to this but I can't seem to get the cookie to save? If I change page or refresh, the cookie seems to revert back to English

 

It's the first piece of code in the header.php file which is used by all my template pages.

 

Any further pointers are much appreciated!

Link to comment
Share on other sites

Thanks

 

This is in my header file:

<?php
$cookie_name = 'defaultLanguage';
// set cookie only when the url contains a value
if(isset($_GET['language'])){
    // note: you should validate $_GET['language'] to insure it contains exactly only one of the permitted values before using it at all
    setcookie($cookie_name, $_GET['language'], time() + (86400 * 30), '/'); // 86400 = 1 day
}
/**
 * @package WordPress
**/
get_header();
include(TEMPLATEPATH."/path.php");
?>
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>

This is a wordpress theme but the site calls this file in so shouldn't be an issue

 

Thanks for your time/assistance, it's really appreciated!

Link to comment
Share on other sites

you need to do some investigating and find out exactly what is occurring and when it is occurring in the process.

 

1) when you change the language setting to specific language, is a cookie being set in your browser with the correct value in it?

 

2) after you refresh the page or redirect does the cookie still exist in the browser with the correct language set in it or has the cookie in the browser been changed to English?

 

3) does the variation of the sub-domain/host-name (i.e. www. vs no www.) in the url in your browser's address bar change when you refresh or redirect?

 

4) does the url have any ?language=xxxxxxxx value it in after you refresh the page or redirect and if so, what is the xxxxxxx value?

 

5) do you have php's error_reporting set to E_ALL and display_errors set to ON so that you would know if there are any php detected errors affecting the setcookie() statement?

 

6) do you have any code that's testing the language setting that could be setting it vs testing it (i.e. one = an assignment, vs two == a comparison)?

 

short-answer - you need to pin down at what point the value is correct, both in the cookie in your browser and in the $_COOKIE that's sent (or not sent) from the browser to the server-side php code, and where it changes to an incorrect value in order to find where and what's causing the problem.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.