Home > Backend Development > PHP Tutorial > How to set and read cookies using php and jquery_PHP tutorial

How to set and read cookies using php and jquery_PHP tutorial

WBOY
Release: 2016-07-21 14:59:35
Original
830 people have browsed it

The HTTP protocol is a stateless protocol, which means that each request you make to the website is independent and therefore cannot save data by itself. But this simplicity is also one of the reasons it spread so widely in the early days of the internet.

However, there is still a way for you to save information between requests in the form of cookies. This approach enables you to manage sessions and maintain data more efficiently.

There are two ways to handle cookies - server (php, asp, etc.) and client (javascript). In this tutorial, we will learn how to create cookies in php and javascript. .

Cookies and php

setting cookies
To create cookies in php you need to use the setcookie method . It requires some parameters (except for the first parameter which is required, other parameters are optional)

Copy code The code is as follows:

setcookie(
'pageVisits', //cookie name, required
$visited, //cookie value
time()+7*24*60*60, //expiration time , set to one week
'/', //The file path available for cookies
'demo.tutorialzine.com' //The domain name bound to the cookie
)

If If the expiration time is set to 0 (the default setting is also 0), the cookie will be lost when the browser is restarted.
The parameter '/' means that all file path cookies under your domain name can be used (of course you can also set a single file path for it, for example: '/admin/').

You can also pass two additional parameters to this function, which are not given here. They are specified as boolean type.
The first parameter indicates that the cookie will only operate on a secure HTTPS connection, while the second parameter indicates that javascript cannot be used to operate the cookie.

For most people, you only need the fourth parameter and ignore the rest.

reading cookies
Reading cookies with php is much simpler. All cookies passed to the script are in the $_COOKIE super global array.
In our example, the following code can be used to read cookies:
Copy the code The code is as follows:

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

It is worth noting that , when the next page is loaded, you can also use $_COOKIE to get the cookies you set using the setcookie method.
You should be aware of something.

deleting cookies
In order to delete cookies, you only need to use the setcookie function to set a past time for the cookies as expiration.
Copy code The code is as follows:

setcookie(
'pageVisits',
$visited,
time()-7*24*60*60, //Set to the previous week, the cookie will be deleted
'/',
'demo.tutorialzine.com'
)

Cookies and jQuery
To use cookies in jquery, you need a plugin Cookie plugin.

Setting cookies
Setting cookies with the Cookie plug-in is very intuitive:
Copy the code The code is as follows:

$(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 cookies is even simpler, just call the $.cookie() method and give it a cookie-name. This method will return the cookie value:
Copy code The code is as follows:

$(document).ready(function(){

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

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

Deleting cookies
To delete cookies, just make it next time For the $.cookie() method, just set the second parameter to null.
Copy code The code is as follows:

$(document).ready(function(){

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

// No more kittens
});

Complete Example:
demo.php
Copy code The code is as follows:

// Always set cookies before any data or HTML are printed to the page
$visited = (int)$_COOKIE['pageVisits'] + 1;
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 all scripts in every folder of the site
   'demo.tutorialzine.com'); // Domain to which the cookie will be locked
?>




MicroTut: Getting And Setting Cookies With jQuery & PHP | Tutorialzine demo






MicroTut: Getting And Setting Cookies With jQuery & PHP


Go Back To The Tutorial »



 

   

The number above indicates how many times you've visited this page (PHP cookie). Reload to test.




   

 

     

        
            Save
       

   

   

Write some text in the field above and click Save. It will be saved between page reloads with a jQuery cookie.






jquery.cookie.js
复制代码 代码如下:

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

styles.css
复制代码 代码如下:

*{
 margin:0;
 padding:0;
}
body{
 /* Setting default text color, background and a font stack */
 color:#555555;
 font-size:0.825em;
 background: #fcfcfc;
 font-family:Arial, Helvetica, sans-serif;
}
.section{
 margin:0 auto 60px;
 text-align:center;
 width:600px;
}
.counter{
 color:#79CEF1;
 font-size:180px;
}
.jq-text{
 display:none;
 color:#79CEF1;
 font-size:80px;
}
p{
 font-size:11px;
 padding:0 200px;
}
form{
 margin-bottom:15px;
}
input[type=text]{
 border:1px solid #BBBBBB;
 color:#444444;
 font-family:Arial,Verdana,Helvetica,sans-serif;
 font-size:14px;
 letter-spacing:1px;
 padding:2px 4px;
}
/* The styles below are only necessary for the styling of the demo page: */
h1{
 background:#F4F4F4;
 border-bottom:1px solid #EEEEEE;
 font-size:20px;
 font-weight:normal;
 margin-bottom:15px;
 padding:15px;
 text-align:center;
}
h2 {
 font-size:12px;
 font-weight:normal;
 padding-right:40px;
 position:relative;
 right:0;
 text-align:right;
 text-transform:uppercase;
 top:-48px;
}
a, a:visited {
 color:#0196e3;
 text-decoration:none;
 outline:none;
}
a:hover{
 text-decoration:underline;
}
.clear{
 clear:both;
}
h1,h2,p.tutInfo{
 font-family:"Myriad Pro",Arial,Helvetica,sans-serif;
}

Conclusion:
Regarding the use of cookies, you need to be careful not to save some sensitive information (such as username, password) in cookies,
Because when every page is loaded, cookies will be passed to the page like headers, and they can easily be intercepted by criminals.
However, with the proper precautions, you can achieve a huge amount of interaction with this simple technique.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328133.htmlTechArticleHTTP protocol is a stateless protocol, which means that each request you make to the website is independent. And therefore cannot save data by itself. But this simplicity is also what makes the internet...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template