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閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容