use saved variable in cookie with php - javascript

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.

Related

Looking to read cookie array in Console

Written this piece of Code to pass array into Cookie
<script>
var products = [];
{
var products = [{
'name': '$1 Silver Membership Trial - Silver-Membership-3-Month',
'price': '279.88',
'quantity': 1
}]
}
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=/";
}
createCookie('products', JSON.stringify(products));
createCookie('revenue', 279.88);
</script>
When trying to this piece Code in Console does not get array value
console.log(JSON.stringify(createCookie.get('products')));
To get all cookies for the current domain you can use document.cookie.
If you want to get a specific cookie, you must work with that string and extract it.
You can use this function to get a cookie buy it's name:
function getCookieByName(cookiename) {
const cookieString = RegExp(cookiename + "=[^;]+").exec(document.cookie);
return decodeURIComponent(!!cookieString ? cookieString.toString().replace(/^[^=]+./, '') : '');
}
and then just call it like this:
console.log(getCookieByName('products'));

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);

Check returning visitors using cookies

I have a blog that requires users to signup via email in order to view the full post. I want to skip this requirement if a user has already signed up.
Here's how it works.
User visits page, if cookie is presen then show content
If cookie is not present, user must signup
User signs up, cookie created.
The problem with my code is that it's post specific. e.g. Let's say we have Post A & Post B. If user opts in Post A, they will need to opt in again on Post B which is not good.
If they opt in on Post A, I want to recognize the cookie on Post B as well.
How can I adjust my code?
if (document.cookie.indexOf("entered_email")>=0) {
jQuery('.hidden-blog').slideDown();
}
$('.snp-subscribeform').on('submit', function() {
$('.hidden-blog').slideDown();
document.cookie="entered_email=true;expire=06/12/2018";
});
You need to set the path on the cookie to "/" which then allows any page on that site to see the cookie. When you do not set a path for the cookie value, it defaults to the path of the current page which restricts the visibility of that cookie to that path only.
Here are some utility functions for dealing with cookies that allow you to set the path or will default the path to "/".
Using these, your code would look like this:
if (readCookie("entered_email") === "1") {
jQuery('.hidden-blog').slideDown();
}
$('.snp-subscribeform').on('submit', function() {
$('.hidden-blog').slideDown();
// cookie path in this function defaults to "/" so all pages on the
// site can access the cookie
createCookie("entered_email", "1", 365 * 3);
});
And, here's the utility cookie management functions:
// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/"
// and can limit which pages on your site can
// read the cookie.
// By default, all pages on the site can read
// the cookie if path is not specified
function createCookie(name, value, days, path) {
var date, expires = "";
path = path || "/";
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=" + path;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}

How to write value in text file using Javascript

I'm working on a number of views per page using JavaScript.
<SCRIPT LANGUAGE="JavaScript">
<!--
var cookiec = document.cookie
if (cookiec != "") {
var eqchr = 0;
for (var cloop = 1; cloop <= cookiec.length; cloop++) {
if (cookiec.charAt(cloop) == "=") {
eqchr=(++cloop);
}
}
var cookiess = 0;
clength=cookiec.length;
cookies="";
for (cloop = eqchr; cloop < clength; cloop++) {
if (cookiec==";") {
cloop=clength;
}
else {
cookies = cookies + cookiec.charAt(cloop);
}
}
cookiess = parseInt(cookies);
document.write("[" + cookiess + "]");
cookiess++;
cookies = cookiess;
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=" + escape(cookies) + "; expires=" + expDate.toGMTString();
}
else {
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=2; expires=" + expDate.toGMTString();
document.write("[1]");
}
// -->
</SCRIPT>
I am using the above JavaScript to calculate the number of views per page and I want to write the data in a text file.
Do you have any suggestions?
If your JavaScript is running in a browser environment, I would highly recommend either using HTML5 localStorage for storing (key, value) pairs or using AJAX to communicate with a server instead of trying to access a file on the client machine which may potentially become a security/privacy issue. Below is a simple example of using localStorage to store a page view count:
if (localStorage.numberOfViews) {
localStorage.numberOfViews = Number(localStorage.numberOfViews) + 1;
} else {
localStorage.numberOfViews = 1;
}
Hope this helps!
Javascript, running in a normal web browser, has very very limited access to the local file system.
So modern web browsers will let you save data to a file in a specialized directory, isolated from everything else.
For the most part, using localStorage (as mentioned by the others), is your best bet.
If you are running under Windows you can create a specialized file called an '.HTA' which runs with the same kind of access and permissions that regular files use.
Attribute LANGUAGE="JavaScript" is deprecated. You can remove it.
Now, replying your question, you can do it with PHP. Send the data when the user enter the page, send it via AJAX to your server and proccess it with PHP.

setting js simple cookie

I've been out of web development for a while now so very rusty.
I need to make a cookie
If the user visits the site > set cookie
If user comes back to site > read cookie
If time since user last arrived is less than 24hrs > set the ID of a div to style="display:none;"
im struggling and would really appreciate some guidance.
thanks so much
With JavaScript you can
- read cookie:
var coo = [],
a;
if(document.cookie != ''){
$.each(document.cookie.split('; '), function(i, val){
a = val.split('=');
coo[a[0]] = a[1];
});
}
here we have a coo with all cookies (coo['Cookie1'] == 'value').
- set cookie:
document.cookie = 'Cookie_1='+'value for this cookie';
BTW code is using jQuery for $.each.
Heres the messy solution i cam up with in case anyone wanted to know:
function nameDefined(ckie,nme)
{
var splitValues
var i
for (i=0;i
tvalue=getCookieValue(nvpair,cname) //Gets the value of the cookie
if (tvalue == cvalue) return true
else return false
}
else return false
}
function redirectLink() {
if (testCookie("here10", "yes")) {
//window.location="here.html" //Go to the location indicating the user has been here
//alert("there");
window.document.getElementById("indicator").style.display = "none";
}
else{
//alert(" not there");
var futdate = new Date() //Get the current time and date
var expdate = futdate.getTime() //Get the milliseconds since Jan 1, 1970
expdate += 10000 //expires in 1 hour(milliseconds)
futdate.setTime(expdate)
var newCookie="here10=yes; path=/;" //Set the new cookie values up
newCookie += " expires=" + futdate.toGMTString()
window.document.cookie=newCookie //Write the cookie
// window.location="not.html" //Go to the location indicating the user has not been here
window.document.getElementById("indicator").style.display = "block";
}
}

Categories