PHP not detecting cookie set by Javascript - php

EDIT: MY BAD, IT WAS A (SERVER SIDE) CACHING ISSUE. Thanks for the help.
I have a site that when visited first checks for cookie "intro" and then if it doesn't exist, redirects it to an intro page.
<?php if (!isset($_COOKIE["intro"])) {
header( 'Location: http://explainasterisk.com/intro/' ) ; } ?>
When the user clicks the "begin" button on the intro page, the cookie is set using:
<script type="text/javascript">
$(document).ready(function () {
$('.home').click(function () {
scroll(0, 0); //scrolltotop
var intro = "intro" //setting cookiename variable
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*365);
document.cookie = intro+"=1"
+ ";expires="+expire.toGMTString();
$('.home').slideUp(3000, function () { //slideUp function
//Nothing
});
});
});
</script>
In Opera and Chrome the cookie is being set, but when I click on the skip button on the intro page (that takes me back to the original page), I'm simply redirected to the Intro page. You can see this live here: http://explainasterisk.com/

if (!isset($_cookie["intro"])) {
is incorrect array name. It should be in CAPS, like this
if (!isset($_COOKIE["intro"])) {
Reference: $_COOKIE
Thanks Brad Christie.

The source of you problem is you don't have error_reporting(E_ALL); in the beginning of your code (and ini_set('display_errors','On'); in development environment).
If you have it, PHP will display error message that there is no $_cookie variable.

You might want to give jquery-cookie a try because it makes setting and handling cookies in javascript with expire dates so much easier.
One simple line:
$.cookie("[cooke name]", "[value]", { expires: [time in days]);
e.g.:
$.cookie("intro", "set", { expires: 365);
Your PHP snippet looks fine to me and - if the cookie is set correctly - should work.

Try adding the path and domain to the end of your cookie:
path=/; domain=.<?php echo $_SERVER['HTTP_HOST']; ?>

the cookie in javascript is being set with domain .explainasterisk.com
So try this before reading the cookie.
ini_set("session.cookie_domain", ".explainasterisk.com");

Related

Cookies and session in php [duplicate]

So I'd rather not use JS/jQuery for this - but I can't seem to get this to work.
I've got a link Hide Updates which I'm trying to set a cookie with.
if($_GET['hideupdates'] == 'hide'){
setcookie("HideUpdates", "hide", time()+60*60*24*5, "/", $vars->networkSite);
}
it "works", but I have to click the link twice.
from "site.com" I can var_dump() the cookie and it comes up NULL
Now I click the link and go to "site.com?hideupdates=hide" and the cookie still comes up NULL
However, from "site.com?hideupdates=hide" when I click the link again - THEN the cookie comes back hide.
Am I missing something? Or do I 'have' to use JS/jQuery for this?
setcookie does not affect the current request. To do that, you also need to manually set the relevant $_COOKIE variable:
setcookie("HideUpdates",$_COOKIE['HideUpdates'] = "hide", time()+60*60*24*5, "/", $vars->networkSite);
The only way to do it is JS or jQuery because, as the other people say, cookies does not affect the current page request.
You need jquery cookie plugin for the jQuery solution. Some servers have problems with jquery.cookie.js (The solution is to rename the file E.g.: jquery.cook.js)
Usage of jquery cookie plugin
Create session cookie:
$.cookie('the_cookie', 'the_value');
Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
Create expiring cookie, valid across entire site:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined
Read all available cookies:
$.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }
Delete cookie:
// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('the_cookie');
// Same path as when the cookie was written...
$.removeCookie('the_cookie', { path: '/' });
You can try localStorage. It works on Chrome, FF and IE9 and up. We do not support IE7-10! Hooray!
IE8 have some issues with localStorage.
Script must be inside the $(document).ready(function() {});
$(document).ready(function() {
$("#btnClick").click(function(e) {
e.preventDefault();
localStorage.setItem('cookieName', 'cookie_value');
window.href.location = "your_new_page.php";
});
//On the same page or other page
if (localStorage.getItem('cookieName')){
//do here what you want
}else{
//do something else
}
});
Cookies don't kick in until after they are set and a new page request is sent. This is because cookies are sent with page requests, they just don't magically appear to a the server.
Your solution is to do a page refresh after setting the cookie.

set cookie variable in jquery

I am trying to set a cookie in jquery using :
$( "a.Edit" ) .click(function() {
$( "#dialog-form" ).dialog( "open" );
var un=$(this ).text();
$.cookie("test", un);
});
but when i use it after that <?php echo $_COOKIE['test'] ?> it wont work the cookie is still not set
any help please
thanks in advance
Use the jquery_cookie() plugin for this.
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Where the_cookie is the name of your cookie. and where the_value of your cookie is the value/function it has to do.
expires 7 means that the cookie wil expire in 7 days (one week)
Path isn't nessesary,
Define the path where the cookie is valid. By default the path of the
cookie is the path of the page where the cookie was created (standard
browser behavior). If you want to make it available for instance
across the entire domain use path: '/'. Default: path of page where
the cookie was created.
You can remove the cookie using:
$.removeCookie('the_cookie');
you can read the cookie using:
$.cookie('the_cookie');
Hope it helps.
It is possible to set the cookie in PHP entirely without jQuery at all..
..however...
It appears you are using jQuery in this way.
What may be causing a problem is a few things:
a) $(this).val() possibly might be returning NULL.
b) You are not setting the path and expiration on the cookie.
If you have subdirectories it is normally good to set a master cookie that is the root path '/'.
To read your cookie using PHP, try this...
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
Can be possible duplicate of Get the cookie value in PHP?
Try using:
$.cookie("example", "foo", { expires: 7 });
Source

My code doesn't return the right value of a cookie generate with Jquery

I'm trying to set two different types of users, visitor or exhibitor on a wordpress website. To do that, i have two links on the top of my header.php.
visitor
exhibitor
Using jquery.cookie.js, I set a cookie called user_type in my js file main.js.
$('a#btn-visiteur').click(function(){
$.cookie('user_type', 'visitor', { expires: 7, path: '/' });
});
$('a#btn-exposant').click(function(){
$.cookie('user_type', 'exhibitor', { expires: 7, path: '/' });
});
Back in my header.php, I just want to show that my cookie is set correctly so i just echo the cookies in my file.
<?php if(isset($_COOKIE['user_type'])){
if($_COOKIE['user_type'] == 'visitor'){
echo 'visitor';
}
if($_COOKIE['user_type'] == 'exhibitor'){
echo 'exhibitor';
}
} ?>
Using Firebug, i see that my cookie is correctly set but my php code doesn't return the right result. It just show the previous value of the cookie.
I hope that its understandable i'm not very comfortable with english. Dear people of stackoverflow, I need your help.
Thank by advance.
Just reload the page after you set the variables.
Example:
$('a#btn-visiteur').on('click',function(){
$.cookie('user_type', 'visitor', { expires: 7, path: '/' });
location.reload();
});

How to use cookie into specific show/hide javascript header. Live example included

With the help of Th0rndike & Pranav, I have make a show/hide header on my site. What I want to do next, is to set a cookie on user's side, so next time this user browses my site, header remains in it's last condition. Live example, on comment below.
I have no idea about cookies, except the very basic stuff, so please, if you have the kindness, be a little bit explanatory to me!!! :)
Thank you in advance!!!
function setCookie(h,a,f){
try{
document.cookie=escape(h)+"="+escape(a)+(f?"; expires=Thu, 31 Dec 2020 23:59:59 GMT":"")+";
path=/";return true;
}catch(c){
alert(c.Message);
}
return false;
}
Try this function
i have created its sets session cookie if you pass parameter to this function
like this :- setCookie('your key','your value',false);
There are two types of cookie one is session and other is persistent cookie,
session cookies expires after a particular session and persistent cookie persist for the amount of time written in your function.
For persistent cookie pass parameter as such setCookie('your key','your value',true);
this is function to get cookie
function getCookie(m){
try{
var f=m+"=";
var l=document.cookie;
var b=-1;
var a=-1;
if(l.length>0){
b=l.indexOf(f);
if(b>-1){
b+=f.length;
a=l.indexOf(";",b);
a=((a==-1)?l.length:a);
g=unescape(l.substring(b,a));
}
}
}catch(h){
alert(h.Message);
}
return g;
}
pass only the key name of cookie as this :- getCookie('your key name');

set PHP cookie on click

So I'd rather not use JS/jQuery for this - but I can't seem to get this to work.
I've got a link Hide Updates which I'm trying to set a cookie with.
if($_GET['hideupdates'] == 'hide'){
setcookie("HideUpdates", "hide", time()+60*60*24*5, "/", $vars->networkSite);
}
it "works", but I have to click the link twice.
from "site.com" I can var_dump() the cookie and it comes up NULL
Now I click the link and go to "site.com?hideupdates=hide" and the cookie still comes up NULL
However, from "site.com?hideupdates=hide" when I click the link again - THEN the cookie comes back hide.
Am I missing something? Or do I 'have' to use JS/jQuery for this?
setcookie does not affect the current request. To do that, you also need to manually set the relevant $_COOKIE variable:
setcookie("HideUpdates",$_COOKIE['HideUpdates'] = "hide", time()+60*60*24*5, "/", $vars->networkSite);
The only way to do it is JS or jQuery because, as the other people say, cookies does not affect the current page request.
You need jquery cookie plugin for the jQuery solution. Some servers have problems with jquery.cookie.js (The solution is to rename the file E.g.: jquery.cook.js)
Usage of jquery cookie plugin
Create session cookie:
$.cookie('the_cookie', 'the_value');
Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
Create expiring cookie, valid across entire site:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined
Read all available cookies:
$.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }
Delete cookie:
// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('the_cookie');
// Same path as when the cookie was written...
$.removeCookie('the_cookie', { path: '/' });
You can try localStorage. It works on Chrome, FF and IE9 and up. We do not support IE7-10! Hooray!
IE8 have some issues with localStorage.
Script must be inside the $(document).ready(function() {});
$(document).ready(function() {
$("#btnClick").click(function(e) {
e.preventDefault();
localStorage.setItem('cookieName', 'cookie_value');
window.href.location = "your_new_page.php";
});
//On the same page or other page
if (localStorage.getItem('cookieName')){
//do here what you want
}else{
//do something else
}
});
Cookies don't kick in until after they are set and a new page request is sent. This is because cookies are sent with page requests, they just don't magically appear to a the server.
Your solution is to do a page refresh after setting the cookie.

Categories