您的位置:首页技术文章
文章详情页

PHP特点之会话机制2——Session及其使用

浏览:5日期:2022-09-15 13:32:26

会话机制(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//注册sessionsession_start();if (!isset($_SESSION[’count’])) { $_SESSION[’count’] = 0;} else { $_SESSION[’count’]++;}//删除sessionunset($_SESSION[’count’]);?>

Session相关函数:

session_cache_expire — Return current cache expiresession_cache_limiter — Get and/or set the current cache limitersession_commit — session_write_close 的别名session_decode — Decodes session data from a session encoded stringsession_destroy — Destroys all data registered to a sessionsession_encode — 将当前会话数据编码为一个字符串session_get_cookie_params — Get the session cookie parameterssession_id — Get and/or set the current session idsession_is_registered — 检查变量是否在会话中已经注册session_module_name — Get and/or set the current session modulesession_name — Get and/or set the current session namesession_regenerate_id — Update the current session id with a newly generated onesession_register_shutdown — Session shutdown functionsession_register — Register one or more global variables with the current sessionsession_save_path — Get and/or set the current session save pathsession_set_cookie_params — Set the session cookie parameterssession_set_save_handler — Sets user-level session storage functionssession_start — Start new or resume existing sessionsession_status — Returns the current session statussession_unregister — Unregister a global variable from the current sessionsession_unset — Free all session variablessession_write_close — Write session data and end session
标签: PHP
相关文章: