The HTTP protocol is a stateless protocol, which means that every request you make to the site is independent and therefore cannot be saved by itself. But this simplicity is one of the reasons it has spread widely in the early days of the Internet.
However, it still has a way to keep information between requests in the form of cookies. This approach allows you to be more efficient in session management and maintenance of data.
There are two ways to handle 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 ways.
Cookies and PHP
Setting cookies
Create cookies in PHP you need to use the Setcookie method. It requires some parameters (except that the first parameter is required and the other parameters are optional)
Copy Code code as follows:
Setcookie (
' Pagevisits ',//cookie name, required
$visited, the value of//cookie
Time () +7*24*60*60,//expiration, set to one weeks
'/',//cookie available file path
' 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.
Parameter '/' means that all file path cookies under your domain name can be used (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 specified as Boolean types.
The first parameter indicates that the cookie operates only at a secure HTTPS connection, while the second parameter indicates that JavaScript cannot be used to manipulate cookies.
For most people, you only need a fourth argument, and the rest is ignored.
Reading cookies
It's much simpler to read cookies in PHP. All the cookies that pass to the script are in the Super Global array $_cookie.
In our example, you can use the following code to read cookies:
Copy Code code 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 obtain cookies that you set with the Setcookie method,
You should be aware of something.
Deleting cookies
In order to remove cookies, just use the Setcookie function for cookies to set a past time to expire on the line.
Copy Code code as follows:
Setcookie (
' Pagevisits ',
$visited,
Time () -7*24*60*60,//set to first one weeks, 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 intuitive to use cookies plug-in to set cookies:
Copy Code code 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's even simpler to read cookies, just call the $.cookie () method, give it a cookie-name, and this method returns the value of the cookie:
Copy Code code 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 have to make the $.cookie () method, and then set the second argument to null.
Copy Code code as follows:
$ (document). Ready (function () {
Deleting the kittens cookie:
var str = $.cookie ("kittens", null);
No More Kittens
});
Complete Example:
demo.php
Copy Code code as follows:
<?php
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 would be available to all scripts in every Folder of the site
' demo.tutorialzine.com '); Domain to which the cookie would be locked
?>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>microtut:getting and Setting Cookies with JQuery & PHP | Tutorialzine demo</title>
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" mce_href= "Styles.css"/>
<mce:script type= "Text/javascript" src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" Mce_ Src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></mce:script>
<mce:script type= "Text/javascript" src= "Jquery.cookie.js" mce_src= "Jquery.cookie.js" ></mce:script>
<mce:script type= "Text/javascript" ><!--
$ (document). Ready (function () {
var cookie = $.cookie (' Democookie ');
If The cookie has been set in a previous page load, show it in the DIV directly:
if (cookie) $ ('. Jq-text '). Text (cookie). Show ();
$ ('. Fields a '). Click (function (e) {
var text = $ (' #inputBox '). Val ();
Setting a cookie with a seven day validity:
$.cookie (' Democookie ', text,{expires:7, Path: '/', Domain: ' demo.tutorialzine.com '});
$ ('. Jq-text '). Text (text). Slidedown (' slow ');
E.preventdefault ();
});
$ (' #form1 '). Submit (function (e) {E.preventdefault ();})
})
--></mce:script>
<body>
<div class= "section" >
<div class= "Counter" ><?php Echo $visited?></div>
<p>the number above indicates how many times you ' ve visited this page (PHP cookie). Reload to Test.</p>
</div>
<div class= "section" >
<div class= "Jq-text" ></div>
<form action= "" method= "Get" id= "Form1" >
<div class= "Fields" >
<input type= "text" id= "InputBox"/>
<a href= "" >Save</a>
</div>
</form>
<p>write some text in the field above and click Save. It'll be saved between page reloads with a jQuery cookie.</p>
</div>
</body>
Jquery.cookie.js
Copy Code code 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 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, have 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/A.
* 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 is a session cookie and won't 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 of the "cookie" is 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 cookies 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 Code code 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 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:
With regard to the use of cookies, you need to be careful not to keep some sensitive information (such as user name, password) in the cookies,
Because when each page is loaded, cookies are passed to the page like headers, which is easily intercepted by the lawless elements.
However, with proper precautions, you can use this simple technique to achieve a lot of interaction.