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() 的值。

推荐阅读更多精彩内容