PHP特點之會話機制2——Session及其使用
會話機制(Session)在 PHP 中用于保存并發(fā)訪問中的一些數(shù)據(jù)。這使可以幫助創(chuàng)建更為人性化的程序,增加站點的吸引力。
一個訪問者訪問你的 web 網站將被分配一個唯一的 id, 就是所謂的會話 id. 這個 id 可以存儲在用戶端的一個 cookie 中,也可以通過 URL 進行傳遞.
會話支持允許你將請求中的數(shù)據(jù)保存在超全局數(shù)組$_SESSION中. 當一個訪問者訪問你的網站,PHP 將自動檢查(如果 session.auto_start被設置為 1)或者在你要求下檢查(明確通過 session_start() 或者隱式通過 session_register()) 當前會話 id 是否是先前發(fā)送的請求創(chuàng)建. 如果是這種情況, 那么先前保存的環(huán)境將被重建.
$_SESSION (和所有已注冊得變量) 將被 PHP 使用內置的序列化方法在請求完成時 進行序列化.序列化方法可以通過session.serialize_handler 這個 PHP 配置選項中來設置一個指定的方法.注冊的變量未定義將被標記為未定義.在并發(fā)訪問時,這些變量不會被會話模塊 定義除非用戶后來定義了它們.
因為會話數(shù)據(jù)是被序列化的,resource 變量不能被存儲在會話中.序列化句柄 (php 和 php_binary) 會受到 register_globals 的限制. 而且,數(shù)字索引或者字符串索引包含的特殊字符(| 和 !) 不能被使用. 使用這些字符將腳本執(zhí)行關閉時的最后出現(xiàn)錯誤. 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相關函數(shù):
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 — 將當前會話數(shù)據(jù)編碼為一個字符串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相關文章:
