codeigniter 臨時(shí)數(shù)據(jù)
在某些情況下,您希望在某個(gè)特定時(shí)間段后刪除會(huì)話中存儲(chǔ)的數(shù)據(jù),這可以使用 codeigniter 中的 tempdata 功能來完成。
添加臨時(shí)數(shù)據(jù)
要將數(shù)據(jù)添加為 tempdata,我們必須使用 mark_as_tempdata() 函數(shù)。此函數(shù)采用兩個(gè)參數(shù)項(xiàng)或要存儲(chǔ)為 tempdata 的項(xiàng),這些項(xiàng)的到期時(shí)間如下所示。
// 'item' will be erased after 300 seconds(5 minutes) $this->session->mark_as_temp('item',300);
你也可以傳遞一個(gè)數(shù)組來存儲(chǔ)多個(gè)數(shù)據(jù)。下面存儲(chǔ)的所有項(xiàng)目將在 300 秒后過期。
$this->session->mark_as_temp(array('item','item2'),300);
您還可以為每個(gè)項(xiàng)目設(shè)置不同的過期時(shí)間,如下所示。
// 'item' will be erased after 300 seconds, while 'item2' // will do so after only 240 seconds $this->session->mark_as_temp(array( 'item'=>300, 'item2'=>240 ));
檢索臨時(shí)數(shù)據(jù)
我們可以使用 tempdata() 函數(shù)檢索臨時(shí)數(shù)據(jù)。此函數(shù)可確保您僅獲取臨時(shí)數(shù)據(jù),而不獲取任何其他數(shù)據(jù)。查看下面給出的示例以了解如何檢索臨時(shí)數(shù)據(jù)。 tempdata() 函數(shù)將采用要獲取的項(xiàng)目的一個(gè)參數(shù)。
$this->session->tempdata('item');
如果省略參數(shù),則可以檢索所有現(xiàn)有的臨時(shí)數(shù)據(jù)。
刪除臨時(shí)數(shù)據(jù)
tempdata 在到期時(shí)間后自動(dòng)刪除,但如果您想在此之前刪除 tempdata,那么您可以使用 unset_tempdata() 函數(shù)執(zhí)行如下所示操作,該函數(shù)將項(xiàng)目的一個(gè)參數(shù)用于被刪除。
$this->session->unset_tempdata('item');
示例
創(chuàng)建一個(gè)名為 tempdata_controller.php 的類并將其保存在 application/controller/tempdata_controller.php 中。
class tempdata_controller extends ci_controller { public function index() { $this--->load->library('session'); $this->load->view('tempdata_view'); } public function add() { $this->load->library('session'); $this->load->helper('url'); //tempdata will be removed after 5 seconds $this->session->set_tempdata('item','item-value',5); redirect('tempdata'); } } ?>
創(chuàng)建一個(gè)名為 tempdata_view.php 的文件并將其保存在 application/views/tempdata_view.php
codeigniter tempdata example temp data exampleecho $this--->session->tempdata('item'); ?>
click here to add temp data.
在 application/config/routes.php 中的 routes.php 文件中進(jìn)行更改,并在文件末尾添加以下行。
$route['tempdata'] = "tempdata_controller"; $route['tempdata/add'] = "tempdata_controller/add";
通過訪問以下鏈接執(zhí)行上述示例。將 yoursite.com 替換為您網(wǎng)站的網(wǎng)址。
http://yoursite.com/index.php/tempdata
訪問上述 url 后,您將看到如下所示的屏幕。
單擊 "單擊此處"鏈接,您將看到如下所示的屏幕。
在此屏幕中,您將看到臨時(shí)數(shù)據(jù)變量的值。五秒后再次刷新同一頁(yè)面,因?yàn)槲覀円呀?jīng)將臨時(shí)數(shù)據(jù)設(shè)置了五秒,您將看到如上所示的屏幕,五秒后臨時(shí)數(shù)據(jù)變量將自動(dòng)刪除。如果在 5 秒前刷新同一個(gè)頁(yè)面,那么臨時(shí)數(shù)據(jù)不會(huì)被刪除,因?yàn)闀r(shí)間段還沒有結(jié)束。
銷毀會(huì)話
在 php 中,我們使用 session_destroy() 函數(shù)來銷毀會(huì)話,而在 codeigniter 中,我們可以銷毀函數(shù),如下所示。
$this->session->sess_destroy();
調(diào)用此函數(shù)后,包括 flashdata和 tempdata在內(nèi)的所有會(huì)話數(shù)據(jù)將被永久刪除且無法找回。
- CodeIgniter 教程
- CodeIgniter 安裝
- CodeIgniter 應(yīng)用程序架構(gòu)
- CodeIgniter MVC 框架
- CodeIgniter 基本概念
- CodeIgniter 配置
- CodeIgniter 使用數(shù)據(jù)庫(kù)
- CodeIgniter 庫(kù)
- Laravel session
- Laravel 驗(yàn)證
- Laravel Facades
- Laravel 契約
- Laravel CSRF保護(hù)
- Laravel 認(rèn)證
- Laravel Artisan控制臺(tái)
- Laravel 加密
- Laravel 哈希
- Laravel 歷史版本記錄