Setting cookie by PHP and reading using JavaScript - php

I use the Laravel PHP framework and set a cookie using Cookie::put(..),
Code to set cookie using Laravel PHP,
Cookie::put('id', $id , 0, '/');
when I looked into it I found cookie is being set to a root path that's good for me.
Now in JS I use a jQuery plugin to read the cookie but it returns null while reading cookie setted by PHP.
JS code to access cookie,
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name){
return unescape(y);
}
}
}
print_r($_COOKIE)
Array ( [id] => 653a8dbd0903d2eacfdfe87bce29640d136a4380+1 [session_payload] => 2c3e260bb766ea1519dcbc3d13025d3ede6e2e63+mSfAHUAPvmFefQbIArozzbQfY0IzZpAeTarpQsHHOseN+SD3xmmUWfUduVYWf7qVu1Rwo2XYIBSBTUt+J1DhbE9sN2yEelpjsHzU0CVw3F1aPpcPh6oSTzIfskr2hHuWIGi5sf1lvD7qRHtcjPOBD700vnQSy2+DIMTNT4eMS7pz85zi9TMpgLQfWbtUUtNQk1SRHwncwgQyp1xhgPqp4d6eLjaZQ2hXBtOgYbC2Ty5xS4e76WCW+dumNMj3hkSfMoDssKnmRTzV7jYUT6a+oH26tZkKOR8EMMh04xHMWlt73aFsL9EZrIXZFKHkOXqU883qThWot//emOpakBKWyA== [laravel_session] => 2729bdfca6fe6e6f3c98d03c11a65915649af09b+ML1G6xZ5YkImViUxm9gOaTo5AT8jyBfqagdoeyAs ) 1
Update:
I really don't know why this was voted down but here,
I want to access the cookie using JS previously added using PHP.

If COOKIE expiry set to 0, the cookie will expire at the end of the session (when the browser closes). So, JS will not read expired COOKIEs
Try setting the COOKIE expiration for longer,
Cookie::put('id', $id , time()+3600, '/'); //set the cookie alive for 1 hour

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.

PHP isset for cookie not working

I am facing some trouble with a conditional statement that uses cookies in PHP.
I would like to change the state of an image based on whether a cookie is set or not. Here is my code (in file MAIN.PHP):
$cookie = "d_content_vote_".$databaseArray['id'];
if(!isset($_COOKIE[$cookie])) {
// display image 1 if cookie is not set
}
else {
// display image 2 if cookie is set
}
The cookie value (of the timestamp) is set in ../INCLUDES/RATING.PHP, and I make an ajax call to that file. In order to debug, I did a print_r($_COOKIE) in RATING.PHP which gave me this:
Array
(
[d_content_vote_1] => 1402726678
[d_content_vote_4] => 1402727148
[PHPSESSID] => effa8778efbe1b3dfb5bb301e359997d
)
However, when I do a print_r($_COOKIE) in MAIN.PHP I do not get the d_content_vote_* cookies, only the session info.
How do I transfer the cookie that is set in rating.php so that I can use it in main.php. I have never faced this problem before.
[Additional info: I'm building the site on a MAMP server now]
I realised that my cookie was being set and the print_r was done in a file in a subdirectory (/includes) and therefore cannot be used in the root directory. In order to make it work in the root directory, I needed to add another attribute to the function:
setcookie($name, $value, $time, "/");
The last parameter "/" ensures that the cookie can be used in the root directory.
What about the cookie remove when a user make the log-out process? In case we use 4 parameters when setting the cookie, do we need to adopt the 4 parameters both in the log-out process?
setcookie($NomeCookieLogOut, "", time()-3600);
OR
setcookie($NomeCookieLogOut, "", time()-3600, "/");

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

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.

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