Read a javascript cookie from php - javascript

I have a task which is compare up to five products from the product list. For that
I have followed following steps:
step 1:
set onclick event when we click add to compare button of each product. In this event I have set cookie by javascript using this code.
// cookie is set by array because of we have to store 1 to 5 products
var comparearray = [productid];
document.cookie = "compareitem" + "=" + comparearray;
It is successfully set the cookie value which holds product id of those are selected to compare.
Step 2: In my PHP file I have tried to retrieve this cookie value.BY,
$cookie_val = $_COOKIE['compareitem '];
But it is not worked. I don't know this kind of concept is worth. If know, give me the instructions how to solve my problem. Thanks in advance.

Since it may be problem with path I suggest to set/get cookie with extended way:
document.cookie="foo=bar; path=/;"
or you can use this function:
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}

Since some people are writing that you can't use cookies set with JS in PHP, I'm going to answer that question now.
Please try to use a cookieSet and cookieGet function, you can use the one from this answer:
How do I create and read a value from cookie?
var createCookie = function(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
Note the last parameter which is written into the cookie.. the path-param is set to '/', so the root location! Use a php script in the root location, so that both use the root location and not some other location.
Next please try to stringify the array with JSON.
var cookiedata = JSON.stringify(comparearray);
Then you should be able to get the cookie with PHP and parse the JSON to get the array back.

Related

How to set/change a cookie via php?

I use this code to change the cookie value in php, or set it if it does not exist yet:
setcookie('maintenance_site_contact_failed', '1', time()+3600, '/', 'entwicklung');
And I am using this code to set a cookie in javascript:
setCookie('maintenance_site_contact_failed', '0', 1);
function setCookie(name,value,days)
{
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
But as you can see in the following screenshot the cookie is created a second time instead of changing the existing one, but the duplicate has a dot in the domain name.
Why is there a dot and why is the cookie created twice?
What I try:
If a user sends my form and the validation fails on serverside, then
I am setting the cookie maintenance_site_contact_failed in the PHP script to 1 so that the client knows that an error happened.
The javascript then checks the value of the cookie, and if the cookie value is 1 then it shows an error and resets the cookie value to 0.
Looks like your cookie is only available to different subdomains because in the php equivalent you're assigning a value for the domain parameter.
Try to do the same inside the Javascript setCookie function:
document.cookie = name + "=" + (value || "") + expires + "; path=/; domain=entwicklung";

use saved variable in cookie with php

For last two weeks I was working on saving a page id in cookies and then retrieve it in some other page.
Finally I solved it but now I have some other problem I want to use this id (the one I saved in cookie and retrieve it) in my php code .
I know javascript is client side code and php is server side code but I have to do this. Please help me out with this.
This is my javascript code which is working great and I get the saved id with this line "+value.favoriteid+"
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var faves = new Array();
$(function(){
var favID;
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
}
$(document.body).on('click','#addTofav',function(){
var fav = {'favoriteid':favID};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4> ';
$('#appendfavs').append(element);
});
});
</script>
Read cookie on php side it is easiest thing after you set them by js.
Any cookies sent to you from the client will automatically be included
into a $_COOKIE auto-global array if variables_order contains "C". If
you wish to assign multiple values to a single cookie, just add [] to
the cookie name.
Depending on register_globals, regular PHP variables can be created
from cookies
Here php are some examples:
<?php
echo $_COOKIE["your cookie name"];
?>
<?php
print_r($_COOKIE);
?>
It's not recommended to rely on them as this
feature is often turned off for the sake of security.
http://php.net/manual/en/features.cookies.php
If you already managed to save to cookie in javascript, then it should be no problem to retrive it in PHP, just use $_COOKIE["COKKIE_NAME"] (Where you ofcourse change COOKIE_NAME, to the name of the cookie you saved in JS)..
Have a look at http://php.net/manual/en/features.cookies.php for more examples.

Set a Javascript Cookie based on URL Params

I'm curious if someone can help a very new Javascript user make sense of how to set a cookie, based on specific URL parameters. I see that pulling the data from the URL using JavaScript is covered in this post:
How can I get query string values in JavaScript?
But I can not figure out how to pull that information into a cookie to store the information throughout a users session on the site.
I would like to grab 3 main URL parameters:
utm_source
utm_medium
utm_campaign
And then store them in a cookie in Google Tag Manager using Javascript.
I can not wrap my head around making this happen. Any help would be greatly appreciated. Sorry I dont have much code to show for reference, but I have been experimenting ( and failing ) for hours now.
Thank you so much for any insight on this.
Cheer,
Melissa
Edit:
Sorry...I wasn't expecting someone to write it for me, I just didn't think my very failed attempts would help anyone see what I was trying to do so I just explained.
Here is my code as of now, and I know it's sort of working. I'm editing a previous cookie that stores the site referrer in a cookie. So as it stands right now, the cookie stores the referrer on the first pageview, then if you go to a different page it will show the {{utm_medium}} and continue to show that throughout the visit. I would like for it to not show the referrer, but output a cookie that displays {{utm_source}} | {{utm_medium}} | {{utm_campaign}} if that's even possible...
Thank you again for any help or pointers or articles. I really appreciate it.
<script> //get referrer info and shorten it
var ref = {{Referrer}}
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
} else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
return domain;
}
ref = extractDomain(ref);
//create cookie
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
var cookie = "";
//check if UTMs are present and set cookie content to the source utm
if ({{utm_source}}) {
createCookie("utmsource", cookie + {{utm_source}}, 1000)
} else if ({{utm_medium}}) {
createCookie("utmsource", cookie + "Email", 1000)
//check if referrer is present and set cookie content to the referrer
} else if ({{utm_campaign}}) {
createCookie("utmsource", cookie + "{{utm_campaign}}", 1000)
} else if {
createCookie("utmsource", cookie + "Email", 1000)
};
</script>
When you use cookie + something, you're not updating the cookie string. So each time you do this, you're just concatenating with the original, empty value of this string. Instead of calling setcookie multiple times, update the cookie string as you test the different variables, then call setcookie at the end with the combined value.
You shouldn't use else if between each test, since that will only add the second variable to the cookie if the first variable didn't exist. But you want all the variables put into the cookie.
var cookie = "";
if ({{utm_source}}) {
cookie += {{utm_source}};
}
if ({{utm_medium}}) {
cookie += ' | ' + {{utm_medium}};
} else {
cookie += ' | Email';
}
if ({{utm_campaign}}) {
cookie += ' | ' + {{utm_campaign}};
} else {
cookie += ' | Email';
}
setcookie('utm_source', cookie, 1000);

Getting multiple cookie values for same cookie different paths

Working on a local url: http://127.0.0.1:8000/qa/
Setting cookies using this JS code:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + newSize + "; " + expires; + "path=/";
}
If I call setCookie from /qa/, I can see that the following cookie has been set:
Name=font; Value=12px; Domain=127.0.0.1; Path=/qa
If I subsequently call setCookie from a different url (eg /qa/profile), I see that a second cookie has been created as follows:
Name=font; Value=12px; Domain=127.0.0.1; Path=/qa
Name=font; Value=18px; Domain=127.0.0.1; Path=/qa/profile
What I want is for any call to setCoookie to override the previous value of the initial cookie so that there is only ever one cookie with name="font" and that its value always reflects the last set value. I thought that specifying "path=/"; in my jquery function would do the trick. But it hasn't. What am I doing wrong?

encoding in vb.net and javascript

I have a javascript function which contain file name, folder id, etc and store the values in cookies, and try to access the value in page load of "FileUploader.aspx". below is my javascript function
function cookieFileUploader(name, value) {
debugger
var date = new Date();
date.setTime(date.getTime() + COOKIEXPIRINGTIME);
var expires = "; expires=" + date.toGMTString();
//var encodedDocumentName = encodeURI(value);
//Encoder.EncodeType = "entity";
//var Encodedoc = Encoder.htmlEncode(value);
//document.cookie = name + "=" + Encodedoc + expires + "; path=/";
document.cookie = name + "=" + value + expires + "; path=/";
winstyle = "width=390, height=335,margin-top=0,scrollbars=no,toolbar=no, menubar=no,resizable=no,directories=no,location=no";
progressIndicatorWindow = window.open("FileUploader.aspx", "mywindow", winstyle);
}
now I want to pass the filename with japanese and chinese characters.while i am doing so the file changed in pageload with some square values. i tried encoding the file name in javascript using encodeURI and try to decode in pageload using server.htmldecode(). Is it right way? if not so please provide me a right solution.I want the filename in pageload event of fileUploader,.aspx
Use encodeURIComponent in javascript and then HttpUtility.UrlDecode on the server - that should do it.

Categories