session 学习总结

参考


(一)session

session: a period of time that is spent doing a particular activity. 做某一项具体活动所花费的一段时间

网上所见一般译为:会话

通过为每个独立用户分配唯一的会话 ID,可以实现针对不同用户分别存储数据的功能。 会话通常被用来在++多个页面请求之间++保存及共享信息

一般来说,会话 ID 通过 cookie 的方式发送到浏览器,并且在服务器端也是通过会话 ID 来取回会话中的数据。 如果请求中不包含会话 ID 信息,那么 PHP 就会创建一个新的会话,并为新创建的会话分配新的 ID。

会话的工作流程很简单。当开始一个会话时,PHP 会尝试从请求中查找会话 ID (通常通过会话 cookie), 如果请求中不包含会话 ID 信息,PHP 就会创建一个新的会话。 会话开始之后,PHP 就会将会话中的数据设置到 $_SESSION 变量中。 当 PHP 停止的时候,它会自动读取 $_SESSION 中的内容,并将其进行序列化, 然后发送给会话保存管理器器来进行保存。

可以通过调用函数 session_start() 来手动开始一个会话;如果配置项 session.auto_start 设置为1, 那么请求开始的时候,会话会自动开始。

PHP 脚本执行完毕之后,会话会自动关闭。 同时,也可以通过调用函数 session_write_close() 来手动关闭会话。


(二)session 函数

  1. session_start —— 开始一个新的会话,或 resume(重新开始?/继续?但按使用经验来看,应该翻译为“继续”比较符合本意)已存在的会话

    Start new or resume existing session

    session_start() 可以创建一个会话,或者基于通过 GET/POST 请求或 cookie 传递的会话标识符来继续当前的会话。

  2. session_destroy —— 销毁一个 session 中的所有数据

    Destroys all data registered to a session

    session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.(session_destroy()会销毁(destroy)所有与当前会话相关的数据。它不会 unset 任何与会话相关的全局变量,也不会 unset 会话 cookie。要再次使用会话变量,必须调用 session_start())。

    In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.(为了彻底销毁会话(比如是用户退出登录),必须同时重置/注销(unset)会话 ID。如果是通过 cookie 传送会话 ID 的,那么客户端的会话 cookie 也必须删除(可以用 setcookie()来删除会话 cookie))。

    Example: Destroying a session with $_SESSION

    <?php
    // Initialize the session.
    // If you are using session_name("something"), don't forget it now!
    session_start();
    
    // Unset all of the session variables.
    $_SESSION = array();
    
    // If it's desired to kill the session, also delete the session cookie.
    // Note: This will destroy the session, and not just the session data!
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    
    // Finally, destroy the session.
    session_destroy();
    ?>
    
  3. session_unset —— 释放所有会话变量

    Free all session variables

    The difference between both session_unset and session_destroy is as follows:
    session_unset just clears out the session for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists. session_unset just remove all session variables. it does not destroy the session....so the session would still be active.

  4. session_abort —— 抛弃 session 数组的改动并结束会话

    Discard session array changes and finish session

  5. session_reset —— 用原始值来 重新初始化 session 数组(用来回滚到之前保存的值?)

    session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION.

  6. session_cache_expire —— 返回目前的缓存到期时间

    Return current cache expire(Returns the current setting of session.cache_expire(在 session.cache_expire 中,单位为:分钟,默认值为 180))

    The manual probably doesn't stress this enough: This has nothing to do with lifetime of a session.

    Whatever you set this setting to, it won't change how long sessions live on your server.

    This only changes HTTP cache expiration time (Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user's cache without having to reload them from the server.

  7. session_cache_limiter —— 获取/设置当前的 cache limiter

    Get and/or set the current cache limiter

    The cache limiter defines which cache control HTTP headers are sent to the client. These headers determine the rules by which the page content may be cached by the client and intermediate proxies.

    Setting the cache limiter to nocache disallows any client/proxy caching.

    A value of public permits caching by proxies and the client, whereas private disallows caching by proxies and permits the client to cache the contents.

    In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla.

    You can avoid this problem by using private_no_expire mode. The Expire header is never sent to the client in this mode.

    Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

    发送的响应头
    public (1)Expires:(根据 session.cache_expire 的设定计算得出);(2)Cache-Control: public, max-age=(根据 session.cache_expire 的设定计算得出);(3)Last-Modified:(会话最后保存时间)
    private_no_expire (1)Cache-Control: private, max-age=(根据 session.cache_expire 的设定计算得出), pre-check=(根据 session.cache_expire 的设定计算得出);(2)Last-Modified: (会话最后保存时间)
    private (1)Expires: Thu, 19 Nov 1981 08:52:00 GMT;(2)Cache-Control: private, max-age=(根据 session.cache_expire 的设定计算得出), pre-check=(根据 session.cache_expire 的设定计算得出);(3)Last-Modified: (会话最后保存时间)
    nocache (1)Expires: Thu, 19 Nov 1981 08:52:00 GMT;(2)Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0;(3)Pragma: no-cache
  8. session_encode —— 编码当前 session 数据

    Encodes the current session data as a session encoded string

    session_encode() 返回一个序列化后的字符串,包含被编码的、储存于 $_SESSION 超全局变量中的当前会话数据。

    请注意,序列方法 和 serialize() 是不一样的。 该序列方法是内置于 PHP 的,能够通过设置 session.serialize_handler 来设置。

    // session_encode() just return the session dataset in a formatted form
    
    session_start();
    
    $_SESSION['login_ok'] = true;
    $_SESSION['nome'] = 'sica';
    $_SESSION['inteiro'] = 34;
    
    echo session_encode();
    
    //this code will print
    //login_ok|b:1;nome|s:4:"sica";inteiro|i:34;
    
  9. session_decode —— 解码 session 数据

    Decodes session data from a session encoded string

  10. session_get_cookie_params —— 获取会话的 cookie 参数,返回值为数组

    Get the session cookie parameters

    Returns an array with the current session cookie information, the array contains the following items:

    • "lifetime" - The lifetime of the cookie in seconds.
    • "path" - The path where information is stored.
    • "domain" - The domain of the cookie.
    • "secure" - The cookie should only be sent over secure connections.
    • "httponly" - The cookie can only be accessed through the HTTP protocol.
  11. session_set_cookie_params —— 设置会话的cookie 参数

    Set the session cookie parameters

  12. session_module_name —— 获取/设置当前的会话模块(名称)(这里的 module 到底是什么,官方文档也语焉不详,但可以参考一下官方文档下的用户评论)

    Get and/or set the current session module

  13. session_name —— 获取/设置当前会话的名称

    Get and/or set the current session name

    string session_name ([ string $name ] )
    Returns the name of the current session. If $name is given and function updates the session name, name of the old session is returned.

  14. session_id —— 获取/设置当前会话的 id

    Get and/or set the current session id

  15. session_regenerate_id —— 用新生成的会话 id 来更新当前的会话 id

    Update the current session id with a newly generated one

    session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

    When session.use_trans_sid is enabled, output must be started after session_regenerate_id() call. Otherwise, old session ID is used.

  16. session_status —— 返回当前会话的状态

    Returns the current session status

    • PHP_SESSION_DISABLED if sessions are disabled.
    • PHP_SESSION_NONE if sessions are enabled, but none exists.
    • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.
  17. session_register_shutdown —— 这个函数用来关闭会话

    Session shutdown function.Registers session_write_close() as a shutdown function.

  18. session_save_path —— 获取/设置当前的会话保存路径

    Get and/or set the current session save path

  19. session_set_save_handler —— 设置用户级的会话存储功能

    Sets user-level session storage functions

  20. session_write_close —— 写入会话数据并结束会话

    Write session data and end session

  21. session_commit —— session_write_close 函数的别名

    Alias of session_write_close


  1. session_register —— 用当前会话注册一个或多个全局变量(This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)

    Register one or more global variables with the current session

  2. session_unregister —— 从当前会话中注销一个全局变量(This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)

    Unregister a global variable from the current session

  3. session_is_registered —— 检查一个全局变量是否在会话中已经被注册(This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)

    Find out whether a global variable is registered in a session


(三)预定义常量

下列常量由 sessions 扩展定义,且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

  • SID (string)

    包含着**会话名称以及会话 ID **的常量,格式为 "name=ID",或者如果会话 ID 已经在适当的会话 cookie 中设定时则为空字符串。 这和 session_id() 返回的是同一个 ID。

  • PHP_SESSION_DISABLED (int)

    自 PHP 5.4.0 起。如果会话已禁用则返回 session_status() 的值。

  • PHP_SESSION_NONE (int)

    自 PHP 5.4.0 起。在会话已启用但是没有会话的时候返回 session_status() 的值。

  • PHP_SESSION_ACTIVE (int)

    自 PHP 5.4.0 起。在一个会话已启用并存在时返回 session_status() 的值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,440评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,814评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,427评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,710评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,625评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,511评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,162评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,311评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,262评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,278评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,989评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,583评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,664评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,904评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,274评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,856评论 2 339

推荐阅读更多精彩内容