May 20, 2013

Storing cookies for future form submissions

Yosef Naser’s Question:

Is there any way to store data submitted in cookies and when the same form is loaded again the text fields are filled with the stored values in cookies ?

I have a shopping website and i don’t wanna require customers to register, so when they order an item and come back again to order another item the form is prefilled with their information.

I’ve looked around but no one seems to mention such thing.

You can use $_COOKIE[] to access and retrieve information stored in cookie.

October 7, 2012

What's the best way use caching data in js on client side?

Question by artzub

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.

  1. What’s the best solution this problem, using cookie or HTML5
    WebStorage?
  2. And may be have other way to solve this task?

Answer by Starx

As much as cross browser compatibility matters, cookie is the only choice rather than web storage.

But the question really depends on what kind of data you are caching?

For what you are trying, cookie and web-storage might not be needed at all.

  • Cookies are used to store configuration related information, rather than actual data itself.
  • Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]

I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.

Update:

Quoting:

data about user activity in some social networks (fb, vk, google+)

Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example

if (Modernizr.localstorage) {
    // browser supports local storage
    // Use this method
} else {
    // browser doesn't support local storage
    // Use Cookie Method
}

[1]: http://en.wikipedia.org/wiki/Web_storage

April 23, 2012

Php cookie only set for 1 second?

Question by Jamie Hutber

Maybe there is a better way around having to use a cookie. But i want to set in my php something to tell the user an error but only have it come on once, if they refresh the page i do no want it there anymore.

$time = (1000);
setcookie("msgtype", $type, time() + ($time), '/');
setcookie("msg", $message, time() + ($time), '/');
print_r($_COOKIE);

So for some reason, if i output the $_cookie directly after it still won’t display this cookie.

Any ideas?

Answer by gopi1410

Instead, when showing the error clear the cookie, rather than having it set for 1 second, so that when it refreshes next time & checks for the cookie it won’t be there and so would not display any error.

Or a better option would be using sessions.

Answer by Starx

You dont need to use cookies for this, using SESSION sounds reasonable.

$_SESSION['error'] = 'soem message';
//Use it when you need and simply remove it afterwards
echo $_SESSION['error'];
unset($_SESSION['error']);
April 19, 2012

How many vars should there be in a cookie?

Question by Ted

While using cURL with some site, I noticed that some files that I requested actually used several variables from the cookie I set up with curl.

Here’s a snapshot:

enter image description here

But when I check my cookie file all it reads is just one value for ASP.NET_SessionId:

www.*******.***  FALSE  /  FALSE  0  ASP.NET_SessionId  ddj24l55lfu11nb1lhuflw55

Of course, the values from the snapshot are taken from my browser (Internet Explorer F12), and that cookie contains Three variables (not one).
Internet Explorer F12 cookie variables Name/Values:

NAME  ASPSESSIONIDSACRDADD 
VALUE  LOONCEMDHCGEJOANEGHHFAFH 

NAME  ASPSESSIONIDSCBRABDC 
VALUE  CMONJEMDNICPNPNFICLAPMFM 

NAME  ASPSESSIONIDQACSBADC 
VALUE  MCBOGLCCKNIDDBOADNMPCLCD 

this is my CURL settings for cookies:

$cookiefile = "d:/cookie.txt";

curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiefile); 

What is it that I may be missingin cURL ?

Thanks!

Answer by Starx

By the nature of the div collection, it looks to be like variables are from different browser sessions.

And Even if its not, its up to developer on how to create your application to set and read the data.

April 11, 2012

checking a cookie exists Login Logoff using jquery / js

Question by SOLDIER-OF-FORTUNE

I have a DNN login/logoff control which isnt working properly. I want to therefore make my own using JS/JQUERY.

When the user is logged in the HTML on the page looks like this:

<a href="javascript:__doPostBack('dnn$dnnLOGIN$cmdLogin','')" class="SkinObject" id="dnn_dnnLOGIN_cmdLogin">Logout</a>

and when they are ‘logged out’ it looks like this:

<a href="javascript:__doPostBack('dnn$dnnLOGIN$cmdLogin','')" class="SkinObject" id="dnn_dnnLOGIN_cmdLogin">Login</a>
  • I would like to check if the cookie has been set, if it has then
    display Logoff link and if it hasnt then display the Login link.

  • Clicking on Login will check if the cookie exists (it should as Login
    was displayed) and take them to the login page.

  • Clicking on Logoff should delete the cookie and the refresh the page
    which will then change the link back to ‘Login’ again because no cookie was found.

I was using this as an example guide: http://jsfiddle.net/MadLittleMods/73vzD/

This is what i have done so far:

HTML:

<a id="dnn_dnnLOGIN_cmdLogin" href="Login">
    Login
</a>

||

<a id="dnn_dnnLOGIN_cmdLogin" href="Logoff">
    Logoff
</a>

<br />

<a id="see" href="#">
    see
</a>

JS:

//set the cookie once user has logged in
//for testing purposes clicking login should set the cookie to 1
//clicking on Logoff 'should' set the cookie to 0
$('#dnn_dnnLOGIN_cmdLogin').live('click', function() {
    var action = $(this).attr('href');
    var cookie_value = (action == 'Login') ? 1 : null;

    $.cookie('DNN-COOKIE', cookie_value);

    return false;
});

// clicking on 'see' should bring up an alert box display the cookie value of 1 or 0
$('#see').live('click', function() {

    alert($.cookie('DNN-COOKIE'));

    return false;
});

Answer by Starx

The demo of cookie is working just fine. Its seems you forgot to include the plugin.

See a working one here


Update:

You can check the preexisting of a cookie like this

var preval = $.cookie('cookie-name');
if(preval != null) {
    //... 
}

Demo

April 10, 2012

Clear cookie via jquery?

Question by SOLDIER-OF-FORTUNE

I have a DNN installation but one of the portals is broken and the “logout” button doesnt seem to clear the cokoie. Is it possible to use jquery to clear a specific cookie? or a seperate ASP.NET page?

Answer by Starx

Sure, Using cookie plugin like this

$.cookie("name", null);

Update:

if($('a[href="webiste.co.uk/en-gb/admin.aspx"]').length) {
    $.cookie("name", null);
}

Update 2: Pure Js

function deleteCookie(name) {
    document.cookie = name+'="";-1; path=/';
}

var login = document.getElementById("loginlink");
login.onclick = function() {
  deleteCookie("name");
};
April 4, 2012

How to write a non-english character cookie using javascript and let php reads it properly

Question by Sami Al-Subhi

my websites sometimes needs to read a javascript cookie using php but sometimes I get weird character set from some users like this `#16 3CFJ) DD%J,’1 while for some users it reads it properly. therefore, I think the problem is in the client-side. I use this method to write cookies:

    var expireDate = new Date();
        expireDate.setMonth(expireDate.getMonth() + 1);
    var value="Sami";
    document.cookie = "name="+value+";path=/;expires="+expireDate.toGMTString();

and this $_COOKIE['name']to read it using php.

Answer by Starx

Cookies cant be handled using headers. So,

Encode your cookie using base64_encode() and decode it using base64_decode() to read it.

To encode/decode in Javascript, this answer might help.

March 23, 2012

Javascript – Cannot call method 'split' of null

Question by Lelly

I have a javascript error that occurs on my site, Im pretty sure I know why, but I dont know how to fix it!

here’s the error:

Uncaught TypeError: Cannot call method 'split' of null

Here’s my JS code:

$(function(e) {
    if (document.cookie.indexOf("login") >= 0) {
        $("a#loggedInUser").html( $.cookie("login").split("|")[0] );
    }
});

I’m just trying to display the username stored in the “login” cookie. Now, im pretty sure the error is because the value returned sometimes isn’t a string, then it doesn’t have the split method, so it causes this error.

How can I fix that? Any ideas?

Thanks!

Answer by Jamund Ferguson

Well you can do something like this to set a default if the value is null.

var login = $.cookie("login") || "";
$("a#loggedInUser").html(login);

Also, if you do that you might not need the document.cookie.indexOf thing.

Answer by Starx

Check the length of the cookie. This way you validate two things at once.

if (document.cookie.indexOf("login") >= 0 && $.cookie("login").length) {
    $("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}
January 4, 2011

storing multiple values of a variable in cookie and comparing

Question by John

How can i store multiple values for a variable in cookie using php, for example
$id = 1,2,4,5
Then how can i compare the stored values with a variable? for example, $new_id=4, i want to check if $new_id value exists in the stored values of $id in cookie.
Thanks for help and have a nice day.

Answer by tdammers

You can store arbitrary strings in cookie elements, so a serialized array should work. Example:

// To store:
$ids = array(1, 2, 3, 4);
setcookie('ids', serialize($ids));

// To retrieve:
$serialized = $_COOKIE['ids'];
$ids = unserialize($serialized);
// sanity check: $ids needs to be an array.
assert(is_array($ids));

// Now let's check:
if (in_array(4, $ids)) {
    // Yes, it's here.
}

A few caveats though:

  • The cookie is completely in the hands of the client, and cookie values should never be trusted. Treat them just like you would treat query string parameters or POST data.
  • Cookies offer very limited storage (IIRC, the standard gives you 4096 bytes to work with).

With these in mind, it might be a better idea to store the array in $_SESSION instead – this will give you virtually unlimited storage, and the only way for the client application to fiddle with the values is through your code.

Answer by Starx

Store array in cookie and then compare them

June 21, 2010

Limit posting to every 30 minutes

Question by jay

Thanks for looking.

I’m trying to write a script to set a cookie after the user posts a comment, limiting them from posting again for 30 minutes. I’m so confused on where to start. Please, could you guys help me out on how I do this?

I’m trying to use this jquery plugin – countdown timer.

Answer by Starx

Use Session

For example, after a post, put the current time + 30 minutes in your session line this
$_SESSION['postTimeFlag'] = time() + 1800;
Then whenever the user is about to post then the session

if(time()>$_SESSION['postTimeFlag']) { 
   //continue posting
}
...

Please fill the form - I will response as fast as I can!