MicroTut: Getting And Setting Cookies With jQuery & PHP

Demo Download

HTTP is a stateless protocol, which means that every request you make to a website is standalone and therefore cannot keep data by itself. But this simplicity is also one of the reasons for its widespread adoption in the early ears of the web.

There is, however, a way to keep information between requests in the form of cookies. This way you can have effective session managemet and persistent data.

There are two ways to work with cookies - server side (PHP, ASP etc) and client side (JavaScript). In this MicroTut we are going to take a look at how cookies are created and read in both PHP and JavaScript.

Cookies and PHP

Setting cookies

To create a cookie in PHP, you need to use the setcookie function. It takes a number of parameters (all except for the first are optional and can be omitted):

setcookie(
    'pageVisits',               // Name of the cookie, required
    $visited,                   // The value of the cookie
    time()+7*24*60*60,          // Expiration time, set for a week in the future
    '/',                        // Folder path the cookie will be available for
    'demo.tutorialzine.com'     // Domain to which the cookie will be bound
);

If you pass 0 as an expiration time (which is the default behavior) the cookie will be lost on browse restart. The "/" parameter indicates that it will be available for all directories of the domain (you can optionally bind a cookie to a single directory with something like /admin/ as a parameter).

There are two additional parameters that you could pass to the function, which are not given here. They are specified with a boolean value. The first one indicates that the cookie would be transferred only on a secure HTTPS connection, and the second that the cookie will not be accessible though JavaScript (introduced in PHP 5.2)

For most practical purposes, you would only need the first four parameters, omitting the rest.

Reading cookies

Reading a cookie with PHP is a lot simpler. All the cookies that were passed to the script are available in the $_COOKIE superglobal array. In our example, to read the cookie we would write the following code:

$visits = (int)$_COOKIE['pageVisits']+1;
echo "You visited this site: ".$visits." times";

It is a good place to note, that cookies set with setcookie are available in the $_COOKIE array on the next page load, which is something you should be aware of.

Deleting cookies

To delete cookies, just use setcookie and give it a time in the past as an expiration date.

setcookie(
    'pageVisits',
    $visited,
    time()-7*24*60*60,      // One week in the past. The cookie will be deleted
    '/',
    'demo.tutorialzine.com'
);

Cookies and jQuery

To use cookies with jQuery, you will need the special Cookie plugin.

Setting cookies

Setting cookies with the Cookie plug-in is quite intuitive:

$(document).ready(function(){

    // Setting a kittens cookie, it will be lost on browser restart:
    $.cookie("kittens","Seven Kittens");

    // Setting demoCookie (as seen in the demonstration):
    $.cookie("demoCookie",text,{expires: 7, path: '/', domain: 'demo.tutorialzine.com'});

    // "text" is a variable holding the string to be saved
});

Reading cookies

Reading a cookie is even simpler. Just call the $.cookie() function with a single cookie-name parameter, and the value of the cookie will be returned:

$(document).ready(function(){

    // Getting the kittens cookie:
    var str = $.cookie("kittens");

    // str now contains "Seven Kittens"
});

Deleting cookies

To delete a cookie, again use the $.cookie() function, but pass null as its second parameter.

$(document).ready(function(){

    // Deleting the kittens cookie:
    var str = $.cookie("kittens",null);

    // No more kittens
});

To wrap it up

In this MicroTut we took a look at setting and reading cookie data. It is a good place to note that you should not store any sensitive information such as usernames or passwords in cookies, as they are transmitted as regular headers on every page load and can be easily sniffed by wrongdoers. However, with proper precautions, you can achieve a great deal of interactivity thanks to this simple technology.

Bootstrap Studio

The revolutionary web design tool for creating responsive websites and apps.

Learn more

Related Articles

Nice one, might come in handy in the near future :)

I really like this 'microtutorials'. They help me a lot :D

Cookie Monster

this microtut made me hungry

Pretty useful when you make your own coding. Thanks!

Atul Kash

Really getting addicted to these microtuts, now I find the normal tuts too long to read.
I would like point out that setting the right path is the most important thing while working with cookies. many tutorials don't mention that and kudos to you for that.

Swat Chap

these microtuts are good stuff

carnitos

great mini tutorial :) i have a question, i'm looking for handle expiration date in hours (not days like the example) how will be?
sorry for the dumb question but i cant find any documentation about expiration in hours, i need to set to 4 hours

carnitos

ok, i got it, if someone need it here's the example to set expiration date to 4 hours:

var date = new Date();
date.setTime(date.getTime() + (240 60 1000)); // 4 hours = 240 mins
$.cookie("demoCookie", value, {path: '/', expires: date});

It's simple and powerfull thanks for tutto!

Ishani Patel

Hi,

i have set cookie value using Jquery but unable to get that value in php.

<script type="text/javascript">
$(document).ready(function() {

    $.cookie(&quot;carids&quot;, &quot;123456&quot;);
    alert($.cookie(&quot;carids&quot;)); //got value here
    }); //end document ready
&lt;/script&gt;

<?php var_dump($_COOKIE); // Blank value?>