Home >Backend Development >PHP Tutorial >Example analysis of the difference between cookie and session in PHP, cookie example analysis_PHP tutorial
Cookies and sessions are very important skills in PHP programming. An in-depth understanding and mastery of the application of cookies and sessions is the basis for PHP programming. This article uses examples to analyze the differences between the two. The specific analysis is as follows:
1.Cookie
A cookie is a mechanism that stores data on a remote browser to track and identify users.
PHP sends cookies in the header information of the http protocol, so the setcookie() function must be called before other information is output to the browser, which is similar to the restriction on the header() function.
1.1 Set cookies:
You can use the setcookie() or setrawcookie() function to set cookies. It can also be set by sending http headers directly to the client.
1.1.1 Use the setcookie() function to set cookies:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )
name: cookie variable name
Value: The value of cookie variable
Expire: The time when the validity period ends,
Path: Valid directory,
domain: valid domain name, unique top-level domain
secure: If the value is 1, the cookie can only be valid on https connections. If it is the default value 0, both http and https can be used.
Example:
<?php $value = 'something from somewhere'; setcookie("TestCookie", $value); /* 简单cookie设置 */ setcookie("TestCookie", $value, time()+3600); /* 有效期1个小时 */ setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); /* 有效目录 /~rasmus,有效域名example.com及其所有子域名 */ ?>
Set multiple cookie variables: setcookie('var[a]','value'); Use arrays to represent variables, but do not use quotation marks for their subscripts. In this way, you can use $_COOKIE['var'][' a'] to read the COOKIE variable.
1.1.2. Use header() to set cookies;
header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com[;...]]");
The following parameters are the same as those listed above for the setcookie function.
For example:
$value = 'something from somewhere'; header("Set-Cookie:name=$value");
1.2 Cookie Reading:
You can directly use PHP’s built-in super global variable $_COOKIE to read the cookie on the browser side.
In the above example, the cookie "TestCookie" is set, now let's read it:
print $_COOKIE['TestCookie'];
Has the COOKIE been exported?!
1.3 Delete cookies
Just set the valid time to be less than the current time, and set the value to empty. For example:
setcookie("name","",time()-1);
Similar to using header().
1.4 Frequently Asked Questions and Answers:
1) There is an error message when using setcookie(). It may be because there is output or spaces before calling setcookie(). It may also be that your document is converted from other character sets, and there may be a BOM signature at the end of the document (that is, in Add some hidden BOM characters to the file content). The solution is to prevent this situation from happening in your document. You can also handle it by using the ob_start() function.
2) $_COOKIE is affected by magic_quotes_gpc and may be automatically escaped
3) When using it, it is necessary to test whether the user supports cookies
1.5 Cookie working mechanism:
Some learners are more impulsive and have no time to study the principles, so I put it later.
a) The server sets a cookie in the client by sending an http Set-Cookie header with the response (multiple cookies require multiple headers).
b) The client automatically sends an http cookie header to the server, and the server receives and reads it.
HTTP/1.x 200 OK X-Powered-By: PHP/5.2.1 Set-Cookie: TestCookie=something from somewhere; path=/ Expires: Thu, 19 Nov 2007 18:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-type: text/html
这一行实现了cookie功能,收到这行后
Set-Cookie: TestCookie=something from somewhere; path=/
浏览器将在客户端的磁盘上创建一个cookie文件,并在里面写入:
TestCookie=something from somewhere;
这一行就是我们用setcookie('TestCookie','something from somewhere','/');的结果.也就是用header('Set-Cookie: TestCookie=something from somewhere; path=/');的结果.
2. Session
session使用过期时间设为0的cookie,并且将一个称为session ID的唯一标识符(一长串字符串),在服务器端同步生成一些session文件(可以自己定义session的保存类型),与用户机关联起来.web应用程序存贮与这些session相关的数据,并且让数据随着用户在页面之间传递.
访问网站的来客会被分配一个唯一的标识符,即所谓的会话 ID。它要么存放在客户端的 cookie,要么经由 URL 传递。
会话支持允许用户注册任意数目的变量并保留给各个请求使用。当来客访问网站时,PHP 会自动(如果 session.auto_start 被设为 1)或在用户请求时(由 session_start() 明确调用或 session_register() 暗中调用)检查请求中是否发送了特定的会话 ID。如果是,则之前保存的环境就被重建。
2.1 sessionID的传送
2.1.1 通过cookie传送sessin ID
使用session_start()调用session,服务器端在生成session文件的同时,生成session ID哈希值和默认值为PHPSESSID的session name,并向客户端发送变量为(默认的是)PHPSESSID(session name),值为一个128位的哈希值.服务器端将通过该cookie与客户端进行交互.
session变量的值经php内部系列化后保存在服务器机器上的文本文件中,和客户端的变量名默认情况下为PHPSESSID的coolie进行对应交互.
即服务器自动发送了http头:
header('Set-Cookie: session_name()=session_id(); path=/');
即
setcookie(session_name(),session_id());
当从该页跳转到的新页面并调用session_start()后,PHP将检查与给定ID相关联的服务器端存贮的session数据,如果没找到,则新建一个数据集.
2.1.2 通过URL传送session ID
只有在用户禁止使用cookie的时候才用这种方法,因为浏览器cookie已经通用,为安全起见,可不用该方法.
<a href="p.php?<?php print session_name() ?>=<?php print session_id() ?>">xxx</a>,
也可以通过POST来传递session值.
2.2 session基本用法实例
<?php // page1.php session_start(); echo 'Welcome to page #1'; /* 创建session变量并给session变量赋值 */ $_SESSION['favcolor'] = 'green'; $_SESSION['animal'] = 'cat'; $_SESSION['time'] = time(); // 如果客户端使用cookie,可直接传递session到page2.php echo '<br /><a href="page2.php">page 2</a>'; // 如果客户端禁用cookie echo '<br /><a href="page2.php?' . SID . '">page 2</a>'; /* 默认php5.2.1下,SID只有在cookie被写入的同时才会有值,如果该session 对应的cookie已经存在,那么SID将为(未定义)空 */ ?>
<?php // page2.php session_start(); print $_SESSION['animal']; // 打印出单个session var_dump($_SESSION); // 打印出page1.php传过来的session值 ?>
2.3 使用session函数控制页面缓存.
很多情况下,我们要确定我们的网页是否在客户端缓存,或要设置缓存的有效时间,比如我们的网页上有些敏感内容并且要登录才能查看,如果缓存到本地了,可以直接打开本地的缓存就可以不登录而浏览到网页了.
使用session_cache_limiter('private');可以控制页面客户端缓存,必须在session_start()之前调用.
控制客户端缓存时间用 session_cache_expire(int);单位(s).也要在session_start()前调用.
这只是使用session的情况下控制缓存的方法,我们还可以在header()中控制控制页面的缓存.
2.4 删除session
要三步实现.
<?php session_destroy(); // 第一步: 删除服务器端session文件,这使用 setcookie(session_name(),'',time()-3600); // 第二步: 删除实际的session: $_SESSION = array(); // 第三步: 删除$_SESSION全局变量数组 ?>
2.5 session在PHP大型web应用中的使用
对于访问量大的站点,用默认的session存贮方式并不适合,目前最优的方法是用数据库存取session.这时,函数bool session_set_save_handler ( callback open, callback close, callback read, callback write, callback destroy, callback gc )就是提供给我们解决这个问题的方案.
该函数使用的6个函数如下:
1.bool open() 用来打开会话存储机制,
2.bool close() 关闭会话存储操作.
3.mixde read() 从存储中装在session数据时使用这个函数
4.bool write() 将给定session ID的所有数据写到存储中
5.bool destroy() 破坏与指定的会话ID相关联的数据
6.bool gc() 对存储系统中的数据进行垃圾收集
例子见php手册session_set_save_handler() 函数.
如果用类来处理,用
session_set_save_handler( array('className','open'), array('className','close'), array('className','read'), array('className','write'), array('className','destroy'), array('className','gc'), )
调用className类中的6个静态方法.className可以换对象就不用调用静态方法,但是用静态成员不用生成对象,性能更好.
2.6 常用session函数:
bool session_start(void); 初始化session
bool session_destroy(void): 删除服务器端session关联文件。
string session_id() 当前session的id
string session_name() 当前存取的session名称,也就是客户端保存session ID的cookie名称.默认PHPSESSID。
array session_get_cookie_params() 与这个session相关联的session的细节.
string session_cache_limiter() 控制使用session的页面的客户端缓存
ini session_cache_expire() 控制客户端缓存时间
bool session_destroy() 删除服务器端保存session信息的文件
void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure [, bool httponly]]]] )设置与这个session相关联的session的细节
bool session_set_save_handler ( callback open, callback close, callback read, callback write, callback destroy, callback gc )定义处理session的函数,(不是使用默认的方式)
bool session_regenerate_id([bool delete_old_session]) 分配新的session id
2.7 session安全问题
攻击者通过投入很大的精力尝试获得现有用户的有效会话ID,有了会话id,他们就有可能能够在系统中拥有与此用户相同的能力.
因此,我们主要解决的思路是效验session ID的有效性.
<?php if(!isset($_SESSION['user_agent'])){ $_SESSION['user_agent'] = $_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']; } /* 如果用户session ID是伪造 */ elseif ($_SESSION['user_agent'] != $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']) { session_regenerate_id(); } ?>
2.8 Session通过cookie传递和通过SID传递的不同:
在php5.2.1的session的默认配置的情况下,当生成session的同时,服务器端将在发送header set-cookie同时生成预定义超级全局变量SID(也就是说,写入cookie和抛出SID是等价的.),当$_COOKIE['PHPSESSID']存在以后,将不再写入cookie,也不再生成超级全局变量SID,此时,SID将是空的.
2.9 session使用实例
<?php /** * 效验session的合法性 * */ function sessionVerify() { if(!isset($_SESSION['user_agent'])){ $_SESSION['user_agent'] = MD5($_SERVER['REMOTE_ADDR'] .$_SERVER['HTTP_USER_AGENT']); } /* 如果用户session ID是伪造,则重新分配session ID */ elseif ($_SESSION['user_agent'] != MD5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'])) { session_regenerate_id(); } } /** * 销毁session * 三步完美实现,不可漏 * */ function sessionDestroy() { session_destroy(); setcookie(session_name(),'',time()-3600); $_SESSION = array(); } ?>
注明: session 出现头信息已经发出的原因与cookie一样.
在php5中,所有php session 的注册表配置选项都是编程时可配置的,一般情况下,我们是不用修改其配置的.要了解php的session注册表配置选项,请参考手册的Session 会话处理函数处.
相信本文所述对大家更好的理解PHP中cookie与session的用法有一定的借鉴价值。
session是为了弥补Web服务无状态会话的一个服务器端保存的一个临时用户数据,根据这个数据,服务器可以重建用户会话信息。
cookie是为了适应本地脚本临时数据存储和与服务器端交互进行会话认证的数据保持功能
简单的说,session需要启用cookie才能正常的使用。
抓取HTTP数据包时,会发现在请求网页内容时发送COOKIE: PHPSESSID=xxxx,而在返回的头信息中包含SET-COOKIE: PHPSESSID=xxxx。如果在头信息中更改了此Cookie的值,将会导致你的用户登录状态发生变化,因为服务器端根据PHPSESSID的值去寻找相应的session文件却未能找到。
如果脱离服务器端只考虑初期HTML+脚本的方式来考虑的话,压根就没有session的文件,因为是静态的页面,不会与服务器发生后续关系(抛开ajax的请求)。所以cookie也就成为脚本运行的本地存储文件。cookie的存在形式为“键名=键值”,以“;"分隔。
持续时长的区别:
cookie有一个定义的时长,超过时长,浏览器将认为过期,会弃用并删除此cookie文件。因此即使服务器端的Session仍存在,因为cookie信息已经丢失,无法找回对应的PHPSESSID的值而无法实现会话的重建。如果不定义超时时长,则在关闭浏览器时自动失效。
session可以指定存在期限,如果超过存在时限之前,此COOKIE中PHPSESSID值对应的Session有过请求会自动延长时长,直到超过时长未请求后会通过回收机制进行清除,但不完全保证可以正常回收。如果被回收后,即使本地仍存有cookie文件,但由于对应PHPSESSID的Session文件已不存在,所以也无法重建会话。
Session stores cookies for the server and for the client.
Yes, the biggest difference between Session and Cookie is here. The following is what I compiled based on the code and related understanding.
Code:
A1.php
57d7e05a5a9c22c096b54a8a644427c9";
echo "CookieValue:".$_COOKIE["CookiesTest"]."0c6dc11e160d3b678d68754cc175188a";
$SessionTest = "dd";
echo $SessionTest;
echo $_SESSION["SessionTest"];
?>
A2.php
fc9edfa1a9afeb336a48371997a7b2c8
Cookie:
(1) Use Used to store consecutive visits to a page. (That is, the value of the local cookie is not a true concept of global change, that is, for A1.php, the corresponding cookie value can be called by adjusting $_COOKIE["XX"], but if you open another A2.php IE browser, you cannot retrieve the cookie value! Therefore, it is not a global concept in the actual sense)
(2) Cookie is stored on the client, and it is not a global concept for Cookie. Stored in the Temp directory of the user's WIN.
Session: (A special cookie. When the cookie is banned, the Session will also be banned, but the Session can be regained through redirection)
(1) Can be used to store user globals the only variable. For Session, you can redirect and obtain the value of Session through Session_start() and perform operations regardless of whether the browsing is opened repeatedly. For example, A1.php above performs Session operations. If you open another IE and use Sessoin_start(); then the corresponding variables of the Session will be re-enabled... The rest of the full text >>