search
HomeBackend DevelopmentPHP TutorialA must-read for newbies: The difference between session and cookie_PHP Tutorial

A must-read for newbies: The difference between session and cookie_PHP Tutorial

Jul 21, 2016 pm 02:59 PM
cookiesessionandthe differenceandnewbieyesBrowseofwebsiterookie

session和cookie是网站浏览中较为常见的两个概念,也是比较难以辨析的两个概念,但它们在点击流及基于用户浏览行为的网站分析中却相当关键。基于网上一些文章和资料的参阅,及作者个人的应用体会,对这两个概念做一个简单的阐述和辨析,希望能与大家共同探讨下。

session和cookie的最大区别在于session是保存在服务端的内存里面,而cookie保存于浏览器或客户端文件里面;session是基于访问的进程,记录了一个访问的开始到结束,当浏览器或进程关闭之后,session也就“消失”了,而cookie更多地被用于标识用户,它可以是长久的,用于用户跟踪和识别唯一用户(Unique Visitor)。

关于session

session被用于表示一个持续的连接状态,在网站访问中一般指代客户端浏览器的进程从开启到结束的过程。session其实就是网站分析的访问(visits)度量,表示一个访问的过程。

session的常见实现形式是会话cookie(session cookie),即未设置过期时间的cookie,这个cookie的默认生命周期为浏览器会话期间,只要关闭浏览器窗口,cookie就消失了。实现机制是当用户发起一个请求的时候,服务器会检查该请求中是否包含sessionid,如果未包含,则系统会创造一个名为JSESSIONID的输出 cookie返回给浏览器(只放入内存,并不存在硬盘中),并将其以HashTable的形式写到服务器的内存里面;当已经包含sessionid是,服务端会检查找到与该session相匹配的信息,如果存在则直接使用该sessionid,若不存在则重新生成新的 session。这里需要注意的是session始终是有服务端创建的,并非浏览器自己生成的。

但是浏览器的cookie被禁止后session就需要用get方法的URL重写的机制或使用POST方法提交隐藏表单的形式来实现。

这里有一个很关键性的注意点,即session失效时间的设置,这里要分两方面来看:浏览器端和服务端。对于浏览器端而言,session与访问进程直接相关,当浏览器被关闭时,session也随之消失;而服务器端的session失效时间一般是人为设置的,目的是能定期地释放内存空间,减小服务器压力,一般的设置为当会话处于非活动状态达20或30分钟时清除该 session,所以浏览器端和服务端的session并非同时消失的,session的中断也并不一定意味着用户一定离开了该网站。目前Google Analytics和Omniture都定义当间隔30分钟没有动作时,算作一次访问结束,所以上图中session的最后一步不只是离开,也有可能是静止、休眠或者发呆的状态。

还有一点需要注意,就是现在的浏览器好像趋向于多进程的session共享,即通过多个标签或页面打开多个进程访问同一网站时共享一个 session cookie,只有当浏览器被关闭时才会被清除,也就是你有可能在标签中关闭了该网站,但只要浏览器未被关闭并且在服务器端的session未失效前重新开启该网站,那么就还是使用原session进行浏览;而某些浏览器在打开多页面时也可能建立独立的session,IE8、Chrome默认都是共享 session的,在IE8中可以通过菜单栏中的文件->新建会话来建立独立session的浏览页面。

关于cookie 

cookie 是一小段文本信息,伴随着用户请求和页面在Web服务器和浏览器之间传递。用户每次访问站点时,Web应用程序都可以读取cookie包含的信息。

The common method that has been introduced in the session implementation mechanism is to use session cookies, and the usual cookies mainly refer to another type of cookie - persistent cookies. Persistent cookies refer to cookie information stored on the client's hard drive (set with a certain validity period). When a user visits a website, the browser will search for it on the local hard drive. Cookies associated with this website. If the cookie exists, the browser will send it to your site through the HTTP header information together with the page request, and then the system will compare the attributes and values ​​in the cookie to see if they are consistent with the information stored on the server , and determine the user as a "first time visitor" or "old customer" based on the comparison results.

Persistent cookies generally save the user's user ID. This information is generated by the server when the user registers or logs in for the first time. A cookie containing the domain name and related information is sent and stored on the client's hard disk file. , and set the cookie expiration time to facilitate automatic user login and website content customization.

The mod_usertrack module that comes with Apache can plant a unique cookie (expires for a long time) to the user when the user first comes to the current website . This cookie is the first time the user comes to the current The IP address of the website plus a random string. At the same time, adding the %{cookie}n field at the end of the custom WEB log can realize the output of cookies in the apache log for data statistics and user tracking.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328164.htmlTechArticleSession and cookie are two common concepts in website browsing, and they are also two concepts that are difficult to distinguish, but They are quite similar in click stream and website analysis based on user browsing behavior...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software