Home > Backend Development > PHP Tutorial > Learning PHP--cookie and session_PHP tutorial

Learning PHP--cookie and session_PHP tutorial

WBOY
Release: 2016-07-13 10:31:45
Original
1142 people have browsed it

Recently, I read a little bit of "PHP Core Technology and Best Practices", looked at cookies and sessions, and gained something. I referenced several blogs based on my previous knowledge to summarize~~

1. PHP 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 Settingscookie

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 cookie

bool setcookie (string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )
name: The name of the cookie, that is, $ _COOKIE The key value of the global array
value: The value of the cookie variable, the parameter is empty, and the value of the cookie is empty. Cookies cannot save boolean values, so 0 represents false and 1 represents true.
expire: The time when the validity period ends, in seconds.
Path: Valid directory, the default is "/", which is valid for the entire domain name. If necessary, you can set it to be valid only in a certain directory.
Domain: Valid domain name, unique top-level domain, defaults to this domain name.
secure: Whether to encrypt cookies for transmission, the default is false. If the value is true, the cookie can only be valid on https connections, if the default value is false, both http and https are available.
httponly: Whether to only use HTTP to access cookies. If it is 1 or true, the client's javascript cannot operate cookies. Using this parameter can reduce the risk of XSS attacks, but not all browsers support this parameter. This parameter is only valid in PHP5.2.0 or above.

Example:

<?<span php
</span><span $value</span> = 'something from somewhere'<span ;

</span><span setcookie</span>("TestCookie", <span $value</span>); <span /*</span><span  简单cookie设置 </span><span */</span>
<span setcookie</span>("TestCookie", <span $value</span>, <span time</span>()+3600); <span /*</span><span  有效期1个小时 </span><span */</span>
<span setcookie</span>("TestCookie", <span $value</span>, <span time</span>()+3600, "/~rasmus/", ".example.com", 1); <span /*</span><span  有效目录 /~rasmus,有效域名example.com及其所有子域名 </span><span */</span>
?>
Copy after login

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.

The functions and parameters of setrawcookie are basically the same as setcookie. The only difference is that setrawcookie does not urlencode the value in the cookie.

Cookies set by PHP on the current page cannot take effect immediately. You have to wait until the next page to see them. If they are set by javascript, they will take effect immediately.

1.1.2. Use header() to set cookie

header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com[;...]]");

The following parameters are the same as the parameters of the setcookie function listed above.
For example:

<?<span php
</span><span $value</span> = 'something from somewhere'<span ;
</span><span header</span>("Set-Cookie:name=<span $value</span>"<span );
</span>?>
Copy after login

1.2 Cookie Reading

You can directly use PHP’s built-in super global variable $_COOKIE to read the cookies on the browser side.
In the above example, cookies are set"TestCookie",现在我们来读取:

<span print</span> <span $_COOKIE</span>['TestCookie'];
Copy after login

1.3 Delete cookie

Delete the cookie without display. If you want to delete the cookie, you should set the expire of the cookie to the expiration time, such as one hour ago, 1970. This time, the browser's deletion mechanism will be automatically triggered, or the value should be set to empty. For example:

<span setcookie</span>("name","",<span time</span>()-1);
Copy after login

Similar to using header().

1.4 Cookie cross-domain and P3P protocol

Normal cookies can only be shared within one application, that is, a cookie can only be obtained by the application that created it. The purpose of realizing cross-domain cookies is to unify the application platform, that is, to realize the currently popular single sign-on. The simplest way is to use the P3P protocol.

P3P was developed by the World Wide Web Consortium to provide Web users with more control over their public information. Web sites that support P3P can declare their privacy policies to visitors. Browsers that support P3P can compare the website's policy with the user's privacy preferences and provide the user with a mismatch warning. Therefore, users can be informed about how web privacy is handled.

First introduce first-party cookies and third-party cookies:

First-party cookies are from or sent to the website you are currently viewing.

Third-party cookies are cookies that originate from, or are sent to, a website other than the website you are currently viewing. Third-party websites often provide content on the website you are viewing. For example, many sites use ads from third-party websites, or iframe the URLs of other websites. These third-party websites may use cookies.

在第三方的网页上加入P3P的header,想浏览器发送P3P协议就可以解决COOKIE共享的问题,如下

<span header</span>("P3P","CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM CNT PRE LOC\"");
Copy after login

1.5 常见问题解决

1) 用setcookie()时有错误提示,可能是因为调用setcookie()前面有输出或空格。也可能你的文档使从其他字符集转换过来,文档后面可能带有BOM签名(就是在文件内容添加一些隐藏的BOM字符)。解决的办法就是使你的文档不出现这种情况。还有通过使用ob_start()函数有也能处理一点。2) $_COOKIE受magic_quotes_gpc影响,可能自动转义3) 使用的时候,有必要测试用户是否支持cookie

1.6 cookie工作机理

a) 服务器通过随着响应发送一个http的Set-Cookie头,在客户机中设置一个cookie(多个cookie要多个头).
b) 客户端自动向服务器端发送一个http的cookie头,服务器接收读取.

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

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已经通用,为安全起见,可不用该方法。
xxx,也可以通过POST来传递session值.

2.2 session基本用法实例

<?<span php
</span><span //</span><span  page1.php</span>
<span session_start</span><span ();
</span><span echo</span> 'Welcome to page #1'<span ;
</span><span /*</span><span  创建session变量并给session变量赋值 </span><span */</span>
<span $_SESSION</span>['favcolor'] = 'green'<span ; 
</span><span $_SESSION</span>['animal'] = 'cat'<span ;
</span><span $_SESSION</span>['time'] = <span time</span><span ();

</span><span //</span><span  如果客户端使用cookie,可直接传递session到page2.php</span>
<span echo</span> '<br /><a href="page2.php">page 2</a>'<span ;

</span><span //</span><span  如果客户端禁用cookie</span>
<span echo</span> '<br /><a href="page2.php?' . SID . '">page 2</a>'<span ; 
</span><span /*</span><span  
 默认php5.2.1下,SID只有在cookie被写入的同时才会有值,如果该session
 对应的cookie已经存在,那么SID将为(未定义)空
 </span><span */</span>
?>

<?<span php
</span><span //</span><span  page2.php</span>
<span session_start</span><span ();
</span><span print</span> <span $_SESSION</span>['animal']; <span //</span><span  打印出单个session</span>
<span var_dump</span>(<span $_SESSION</span>); <span //</span><span  打印出page1.php传过来的session值</span>
?>
Copy after login

2.3 使用session函数控制页面缓存

使用session_cache_limiter('private');可以控制页面客户端缓存,必须在session_start()之前调用。控制客户端缓存时间用 session_cache_expire(int);单位(s)。也要在session_start()前调用。这只是使用session的情况下控制缓存的方法,我们还可以在header()中控制控制页面的缓存。

2.4 删除session

要三步实现

<?<span php
</span><span session_destroy</span>();                                      <span //</span><span  第一步: 删除服务器端session文件,这使用 </span>
<span setcookie</span>(<span session_name</span>(),'',<span time</span>()-3600);  <span //</span><span  第二步: 删除实际的session: </span>
<span $_SESSION</span> = <span array</span>();                                  <span //</span><span  第三步: 删除$_SESSION全局变量数组</span>
?>
Copy after login

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可以换对象就不用调用静态方法,但是用静态成员不用生成对象,性能更好。

session存入mysql数据库表可以使用MEMORY引擎,MEMORY引擎采用内存表,所有数据存储在内存,操作速度快,对于session这种形式的数据正好适用,但在大流量的网站中,Session入库存在效率不高、占数据库connection资源等问题。针对这种情况,可以使用Memcached、Redis等Key-Value数据存储方案实现高并发、大流量的Session存储。

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的有效性.

<?<span php

</span><span if</span>(!<span isset</span>(<span $_SESSION</span>['user_agent'<span ])){
    </span><span $_SESSION</span>['user_agent'] = <span $_SERVER</span>['REMOTE_ADDR'].<span $_SERVER</span>['HTTP_USER_AGENT'<span ];
}

</span><span /*</span><span  如果用户session ID是伪造 </span><span */</span>
<span elseif</span> (<span $_SESSION</span>['user_agent'] != <span $_SERVER</span>['REMOTE_ADDR'] . <span $_SERVER</span>['HTTP_USER_AGENT'<span ]) {
    </span><span session_regenerate_id</span><span ();
}
</span>?>
Copy after login

2.9 session使用实例

<?<span php
</span><span /*</span><span *
 * 效验session的合法性
 *
 </span><span */</span>
<span function</span><span  sessionVerify() {
    </span><span if</span>(!<span isset</span>(<span $_SESSION</span>['user_agent'<span ])){
        </span><span $_SESSION</span>['user_agent'] = <span MD5</span>(<span $_SERVER</span>['REMOTE_ADDR'<span ]
        </span>.<span $_SERVER</span>['HTTP_USER_AGENT'<span ]);
    }
    </span><span /*</span><span  如果用户session ID是伪造,则重新分配session ID </span><span */</span>
    <span elseif</span> (<span $_SESSION</span>['user_agent'] != <span MD5</span>(<span $_SERVER</span>['REMOTE_ADDR'<span ] 
    </span>. <span $_SERVER</span>['HTTP_USER_AGENT'<span ])) {
        </span><span session_regenerate_id</span><span ();
    }
}

</span><span /*</span><span *
 * 销毁session
 * 三步完美实现,不可漏
 *
 </span><span */</span>
<span function</span><span  sessionDestroy() {
    </span><span session_destroy</span><span ();
    </span><span setcookie</span>(<span session_name</span>(),'',<span time</span>()-3600<span );
    </span><span $_SESSION</span> = <span array</span><span ();
}
</span>?> 
Copy after login

注明: <br>

    session 出现头信息已经发出的原因与cookie一样.<br>    在php5中,所有php session 的注册表配置选项都是编程时可配置的,一般情况下,我们是不用修改其配置的。要了解php的session注册表配置选项,请参考手册的Session 会话处理函数处。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/761105.htmlTechArticle最近读了一点《PHP核心技术与最佳实践》,看了cookie和session,有所收获,结合之前的认识参考了几篇博客,总结一下~~ 1.PHP的COOKIE cook...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template