PHP特點(diǎn)之會(huì)話機(jī)制2——Session及其使用
會(huì)話機(jī)制(Session)在 PHP 中用于保存并發(fā)訪問(wèn)中的一些數(shù)據(jù)。這使可以幫助創(chuàng)建更為人性化的程序,增加站點(diǎn)的吸引力。
一個(gè)訪問(wèn)者訪問(wèn)你的 web 網(wǎng)站將被分配一個(gè)唯一的 id, 就是所謂的會(huì)話 id. 這個(gè) id 可以存儲(chǔ)在用戶端的一個(gè) cookie 中,也可以通過(guò) URL 進(jìn)行傳遞.
會(huì)話支持允許你將請(qǐng)求中的數(shù)據(jù)保存在超全局?jǐn)?shù)組$_SESSION中. 當(dāng)一個(gè)訪問(wèn)者訪問(wèn)你的網(wǎng)站,PHP 將自動(dòng)檢查(如果 session.auto_start被設(shè)置為 1)或者在你要求下檢查(明確通過(guò) session_start() 或者隱式通過(guò) session_register()) 當(dāng)前會(huì)話 id 是否是先前發(fā)送的請(qǐng)求創(chuàng)建. 如果是這種情況, 那么先前保存的環(huán)境將被重建.
$_SESSION (和所有已注冊(cè)得變量) 將被 PHP 使用內(nèi)置的序列化方法在請(qǐng)求完成時(shí) 進(jìn)行序列化.序列化方法可以通過(guò)session.serialize_handler 這個(gè) PHP 配置選項(xiàng)中來(lái)設(shè)置一個(gè)指定的方法.注冊(cè)的變量未定義將被標(biāo)記為未定義.在并發(fā)訪問(wèn)時(shí),這些變量不會(huì)被會(huì)話模塊 定義除非用戶后來(lái)定義了它們.
因?yàn)闀?huì)話數(shù)據(jù)是被序列化的,resource 變量不能被存儲(chǔ)在會(huì)話中.序列化句柄 (php 和 php_binary) 會(huì)受到 register_globals 的限制. 而且,數(shù)字索引或者字符串索引包含的特殊字符(| 和 !) 不能被使用. 使用這些字符將腳本執(zhí)行關(guān)閉時(shí)的最后出現(xiàn)錯(cuò)誤. php_serialize 沒有這樣的限制.php_serialize 從 PHP 5.5.4 以后可用.
示例一、session的簡(jiǎn)單使用:
<?php//注冊(cè)sessionsession_start();if (!isset($_SESSION[’count’])) { $_SESSION[’count’] = 0;} else { $_SESSION[’count’]++;}//刪除sessionunset($_SESSION[’count’]);?>
Session相關(guān)函數(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 — 將當(dāng)前會(huì)話數(shù)據(jù)編碼為一個(gè)字符串session_get_cookie_params — Get the session cookie parameterssession_id — Get and/or set the current session idsession_is_registered — 檢查變量是否在會(huì)話中已經(jīng)注冊(cè)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相關(guān)文章:
1. PHP循環(huán)與分支知識(shí)點(diǎn)梳理2. 解決ajax請(qǐng)求后臺(tái),有時(shí)收不到返回值的問(wèn)題3. 關(guān)于Ajax跨域問(wèn)題及解決方案詳析4. XML入門的常見問(wèn)題(一)5. JavaWeb Servlet中url-pattern的使用6. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法7. JS中map和parseInt的用法詳解8. jsp EL表達(dá)式詳解9. XML入門的常見問(wèn)題(二)10. JSP之表單提交get和post的區(qū)別詳解及實(shí)例
