php--Session及其使用

伊谢尔伦
伊谢尔伦 原创
2016-11-22 10:32:37 872浏览

会话机制(Session)在 PHP 中用于保存并发访问中的一些数据。这使可以帮助创建更为人性化的程序,增加站点的吸引力。

一个访问者访问你的 web 网站将被分配一个唯一的 id, 就是所谓的会话 id. 这个 id 可以存储在用户端的一个 cookie 中,也可以通过 URL 进行传递.

会话支持允许你将请求中的数据保存在超全局数组$_SESSION中. 当一个访问者访问你的网站,PHP 将自动检查(如果 session.auto_start被设置为 1)或者在你要求下检查(明确通过 session_start() 或者隐式通过 session_register()) 当前会话 id 是否是先前发送的请求创建. 如果是这种情况, 那么先前保存的环境将被重建.

$_SESSION (和所有已注册得变量) 将被 PHP 使用内置的序列化方法在请求完成时 进行序列化.序列化方法可以通过session.serialize_handler 这个 PHP 配置选项中来设置一个指定的方法.注册的变量未定义将被标记为未定义.在并发访问时,这些变量不会被会话模块 定义除非用户后来定义了它们.

因为会话数据是被序列化的,resource 变量不能被存储在会话中.序列化句柄 (php 和 php_binary) 会受到 register_globals 的限制. 而且,数字索引或者字符串索引包含的特殊字符(| 和 !) 不能被使用. 使用这些字符将脚本执行关闭时的最后出现错误. php_serialize 没有这样的限制.php_serialize 从 PHP 5.5.4 以后可用.

示例一、session的简单使用:

<?php
//注册session
session_start();
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
} else {
    $_SESSION['count']++;
}
//删除session
unset($_SESSION['count']);
?>

Session相关函数:

session_cache_expire — Return current cache expire

session_cache_limiter — Get and/or set the current cache limiter

session_commit — session_write_close 的别名

session_decode — Decodes session data from a session encoded string

session_destroy — Destroys all data registered to a session

session_encode — 将当前会话数据编码为一个字符串

session_get_cookie_params — Get the session cookie parameters

session_id — Get and/or set the current session id

session_is_registered — 检查变量是否在会话中已经注册

session_module_name — Get and/or set the current session module

session_name — Get and/or set the current session name

session_regenerate_id — Update the current session id with a newly generated one

session_register_shutdown — Session shutdown function

session_register — Register one or more global variables with the current session

session_save_path — Get and/or set the current session save path

session_set_cookie_params — Set the session cookie parameters

session_set_save_handler — Sets user-level session storage functions

session_start — Start new or resume existing session

session_status — Returns the current session status

session_unregister — Unregister a global variable from the current session

session_unset — Free all session variables

session_write_close — Write session data and end session


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。