How to use PHP and jquery to set up and read cookies_php tutorials

Source: Internet
Author: User
Tags set cookie
The HTTP protocol is a stateless protocol, which means that every request you make to a site is independent and therefore cannot be saved by itself. But this simplicity is one of the reasons for its widespread spread in the early days of the Internet.

However, it still has a way to keep the information between requests in the form of cookies. This approach enables you to manage and maintain data more efficiently.

There are two ways to process cookies-the server side (php,asp, etc.) and the client (JavaScript). In this tutorial, we will learn how to create cookies in both PHP and JavaScript.

Cookies and PHP

Setting cookies
To create a cookie in PHP you need to use the Setcookie method. It needs some parameters (except the first one is required, the other parameters are optional)
Copy CodeThe code is as follows:
Setcookie (
' Pagevisits ',//cookie name, required
$visited, the value of//cookie
Time () +7*24*60*60,//expiration, set to one weeks
'/',//cookie the available file paths
' demo.tutorialzine.com '//cookie bound domain name
)

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

You can also pass this function to two additional parameters, which are not given here. They are defined as a Boolean type.
The first parameter indicates that the cookie operates only on a secure HTTPS connection, and the second parameter indicates that the cookie cannot be manipulated using JavaScript.

For most people, you only need a fourth parameter, and the rest is ignored.

reading Cookies
It's a lot easier to read cookies in PHP. All of the cookies passed to the script are $_cookie in this super global array.
In our example, the following code can be used to read cookies:
Copy CodeThe code is as follows:
$visits = (int) $_cookie[' pagevisits ']+1;
echo "You visited this site:". $visits. "Times";

It is important to note that when the next page loads well, you can also use $_cookie to get the cookies you set with the Setcookie method,
You should be aware of what.

Deleting cookies
In order to delete cookies, it is only necessary to use the Setcookie function for cookies to set a past time as expired.
Copy CodeThe code is as follows:
Setcookie (
' Pagevisits ',
$visited,
Time () -7*24*60*60,//set to the first one weeks, the cookie will be deleted
'/',
' Demo.tutorialzine.com '
)

Cookies and JQuery
To use cookies in jquery, you need a plugin cookie plugin.

Setting Cookies
It is very intuitive to set cookies with a cookie plug-in:
Copy CodeThe code is as follows:
$ (document). Ready (function () {

Setting A kittens cookie, it'll 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
It is even simpler to read a cookie, just call the $.cookie () method, give it a cookie-name, and this method returns the value of the cookie:
Copy CodeThe code is as follows:
$ (document). Ready (function () {

Getting The kittens Cookie:
var str = $.cookie ("kittens");

STR now contains "Seven kittens"
});

Deleting Cookies
To delete a cookie, you only need to make the $.cookie () method in a second and set the second parameter to NULL.
Copy CodeThe code is as follows:
$ (document). Ready (function () {

Deleting The kittens Cookie:
var str = $.cookie ("kittens", null);

No More Kittens
});

Complete Example:
demo.php
Copy CodeThe code is as follows:
Always set cookie before any data or HTML is 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
'/',//folder path, the cookie is available for all scripts in every folder of the site
' demo.tutorialzine.com '); Domain to which the cookie would be locked
?>




<title>Microtut:getting and Setting Cookies with JQuery & PHP | Tutorialzine Demo</title>






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.






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






Jquery.cookie.js
Copy CodeThe code is as follows:
/**
* 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 the 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 so you had to use the same path and domain
* Used when the cookie is 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 would be deleted.
* If set to NULL or omitted, the cookie would be a session cookie and won't be retained
* When 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 would be set and the cookie transmission would
* 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 isn't 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
Copy CodeThe code is as follows:
*{
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 is 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;
}

Concluding remarks:
With regard to the use of cookies, you should be careful not to keep sensitive information (such as user name, password) in cookies,
Because when each page is loaded, the cookie will be passed on to the page like headers, which is easily intercepted by the illegal elements.
However, with proper precautions, you can use this simple technique to achieve a great deal of interaction.

http://www.bkjia.com/PHPjc/328133.html www.bkjia.com true http://www.bkjia.com/PHPjc/328133.html techarticle The HTTP protocol is a stateless protocol, which means that every request you make to a site is independent and therefore cannot be saved by itself. But this simplicity is also it in the Internet ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.