How to use php and jquery to set and read cookies_PHP tutorial

Source: Internet
Author: User
Tags set cookie
How to use php and jquery to set and read cookies. HTTP is a stateless protocol, which means that every request to the website is independent, and therefore data cannot be stored by itself. However, this simplicity is also a stateless protocol in the Internet HTTP protocol, which means that you are independent of every request to the website and therefore cannot store data through it. But this simplicity is also one of the reasons it spread widely in the early days of the Internet.

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

There are two methods to process 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 a cookie in php, you need to use the setcookie method. It requires some parameters (except the first parameter is required, other parameters are optional)

The code is as follows:


Setcookie (
'Pagevisits ', // cookie name, required
$ Visited, // cookie value
Time () + 7*24*60*60, // Expiration time, set to a week
'/', // The available file path of the cookie
'Demo .tutorialine.com '// domain name bound to the cookie
)


If the Expiration Time is set to 0 (the default value is 0), the cookie will be lost when the browser restarts.
The '/' parameter indicates that all file paths under your domain name can be used as cookies (you can also set a single file path for it, for example, '/admin /').

You can also pass this function two additional parameters, which are not provided here. They are specified as boolean type.
The first parameter indicates that the cookie runs only on a secure HTTPS connection, and the second parameter indicates that the cookie cannot be operated using javascript.

For most people, you only need the fourth parameter, and the rest will be ignored.

Reading cookies
Using php to read cookies is much easier. All the cookies passed to the script are in the $ _ COOKIE Super Global array.
In our example, we can use the following code to read cookies:

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 use $ _ COOKIE to obtain the cookies you set using the setcookie method,
You should be aware of something.

Cookies ing cookies
To delete cookies, you only need to use the setcookie function to set an expiration date for cookies.

The code is as follows:


Setcookie (
'Pagevisits ',
$ Visited,
Time ()-7*24*60*60, // if it is set to the previous week, the cookie will be deleted
'/',
'Demo .tutorialine.com'
)


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

Setting cookies
Setting cookies with cookies plug-in is intuitive:

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 .tutorialine.com '});

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


Reading cookies
To read a cookie, you only need to call the $. cookie () method and give it a cookie-name. this method will return the cookie value:

The code is as follows:


$ (Document). ready (function (){

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

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


Cookies ing cookies
To delete a cookie, you only need to set the second parameter to null in the $. cookie () method.

The code is as follows:


$ (Document). ready (function (){

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

// No more kittens
});


Complete example:
Demo. php

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 .tutorialine.com '); // Domain to which the cookie will be locked
?>




MicroTut: Getting And Setting Cookies With jQuery & PHP | tutorialine 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.






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






Jquery. cookie. js

The 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 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 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 * 24x60*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

The 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 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:
When using cookies, you must note that you do not store sensitive information (such as user names and passwords) in cookies,
When a page is loaded, cookies are transmitted to the page like headers, which is easily intercepted by criminals.
However, with proper preventive measures, you can use this simple technology to achieve a large amount of interaction.

Bytes. But this simplicity is also 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.