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 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.

命名管道是一种在操作系统中相对比较低级的进程通信方式,它是一种以文件为中介的进程通信方式。在Go语言中,通过os包提供了对命名管道的支持。在本文中,我们将介绍如何在Go中使用命名管道来实现进程间通信。一、命名管道的概念命名管道是一种特殊的文件,可以被多个进程同时访问。在Linux系统中,命名管道是一种特殊的文件类型,它们存在于文件系统的某个位置上,并且可以在

在Go语言中,使用第三方库是非常方便的。许多优秀的第三方库和框架可以帮助我们快速地开发应用程序,同时也减少了我们自己编写代码的工作量。但是如何正确地使用第三方库,确保其稳定性和可靠性,是我们必须了解的一个问题。本文将从以下几个方面介绍如何使用第三方库,并结合具体例子进行讲解。一、第三方库的获取Go语言中获取第三方库有以下两种方式:1.使用goget命令首先

随着传统的多线程模型在高并发场景下的性能瓶颈,协程成为了PHP编程领域的热门话题。协程是一种轻量级的线程,能够在单线程中实现多任务的并发执行。在PHP的语言生态中,协程得到了广泛的应用,比如Swoole、Workerman等框架就提供了对协程的支持。那么,如何在PHP中使用协程呢?本文将介绍一些基本的使用方法以及常见的注意事项,帮助读者了解协程的运作原理,以

数据聚合函数是一种用于处理数据库表中多行数据的函数。在PHP中使用数据聚合函数可以使得我们方便地进行数据分析和处理,例如求和、平均数、最大值、最小值等。下面将介绍如何在PHP中使用数据聚合函数。一、介绍常用的数据聚合函数COUNT():计算某一列的行数。SUM():计算某一列的总和。AVG():计算某一列的平均值。MAX():取出某一列的最大值。MIN():

变量函数是指可以使用变量来调用函数的一种特殊语法。在PHP中,变量函数是非常有用的,因为它可以让我们更加灵活地使用函数。在本文中,我们将介绍如何在PHP中使用变量函数。定义变量函数在PHP中,变量函数的定义方式非常简单,只需要将要调用的函数名赋值给一个变量即可。例如,下面的代码定义了一个变量函数:$func='var_dump';这里将var_dump函

随着音频处理在各种应用场景中的普及,越来越多的程序员开始使用Go编写音频处理程序。Go语言作为一种现代化的编程语言,具有优秀的并发性和高效率的特点,使用它进行音频处理十分方便。本文将介绍如何在Go中使用音频处理技术,包括读取、写入、处理和分析音频数据等方面的内容。一、读取音频数据在Go中读取音频数据有多种方式。其中比较常用的是使用第三方库进行读取,比如go-

在Go语言中,嵌套结构是一种非常常见的技术。通过将一个结构体嵌入到另一个结构体中,我们可以将复杂的数据模型分解成更小的部分,使其易于理解和维护。本篇文章将介绍如何在Go中使用嵌套结构以及一些最佳实践。一、定义嵌套结构首先,我们需要定义一个包含嵌套结构的结构体。下面的代码演示了如何定义一个包含Person结构体的Company结构体:typePersons

<p>Windows 系统上的 OneDrive 应用程序允许您将文件存储在高达 5 GB 的云上。OneDrive 应用程序中还有另一个功能,它允许用户选择一个选项,是将文件保留在系统空间上还是在线提供,而不占用您的系统存储空间。此功能称为按需文件。在这篇文章中,我们进一步探索了此功能,并解释了有关如何在 Windows 11 电脑上的 OneDrive 中按需使用文件的各种选项。</p><h2>如何使用 On


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment