How to set and read cookies using php and jquery_PHP tutorial
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)
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:
$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.
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:
$(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:
$(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.
$(document).ready(function(){
/ / Deleting the kittens cookie:
var str = $.cookie("kittens",null);
// No more kittens
});
Complete Example:
demo.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 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
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
/**
* 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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
