?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
Session類允許您在瀏覽您的網(wǎng)站時(shí)維護(hù)用戶的“狀態(tài)”并跟蹤他們的活動(dòng)。
CodeIgniter帶有幾個(gè)會(huì)話存儲(chǔ)驅(qū)動(dòng)程序:
文件(默認(rèn);基于文件系統(tǒng))
數(shù)據(jù)庫(kù)
重復(fù)
memcached的
另外,您可以基于其他類型的存儲(chǔ)創(chuàng)建自己的自定義會(huì)話驅(qū)動(dòng)程序,同時(shí)仍然利用Session類的功能。
使用會(huì)話類
關(guān)于并發(fā)性的說(shuō)明
初始化會(huì)話
會(huì)話如何工作?
- [What is Session Data?](about:blank#what-is-session-data)- [Retrieving Session Data](about:blank#retrieving-session-data)- [Adding Session Data](about:blank#adding-session-data)- [Removing Session Data](about:blank#removing-session-data)- [Flashdata](about:blank#flashdata)- [Tempdata](about:blank#tempdata)- [Destroying a Session](about:blank#destroying-a-session)- [Accessing session metadata](about:blank#accessing-session-metadata)- [Session Preferences](about:blank#session-preferences)- [Session Drivers](about:blank#session-drivers) - [Files Driver](about:blank#files-driver) - [Bonus Tip](about:blank#bonus-tip)
- [Database Driver](about:blank#database-driver) - [Redis Driver](about:blank#redis-driver) - [Memcached Driver](about:blank#memcached-driver) - [Bonus Tip](about:blank#id1)
- [Custom Drivers](about:blank#custom-drivers)
類參考
會(huì)話通常會(huì)在每次頁(yè)面加載時(shí)全局運(yùn)行,因此Session類應(yīng)該在控制器構(gòu)造函數(shù)中初始化,或者可以由系統(tǒng)自動(dòng)加載。在大多數(shù)情況下,會(huì)話類將在后臺(tái)無(wú)人值守運(yùn)行,因此只需初始化該類就可以在必要時(shí)讀取,創(chuàng)建和更新會(huì)話。
要在控制器構(gòu)造函數(shù)中手動(dòng)初始化Session類,請(qǐng)使用以下$this->load->library()
方法:
$this->load->library('session');
加載后,會(huì)話庫(kù)對(duì)象將可用:
$this->session
重要
由于Loader類是由CodeIgniter的基本控制器實(shí)例化的,因此請(qǐng)務(wù)必parent::__construct()
在嘗試從控制器構(gòu)造函數(shù)中加載庫(kù)之前進(jìn)行調(diào)用。
加載頁(yè)面時(shí),會(huì)話類將檢查用戶瀏覽器是否發(fā)送有效的會(huì)話cookie。如果會(huì)話Cookie并不不存在(或者如果它不匹配一個(gè)存儲(chǔ)在服務(wù)器上或已過(guò)期)的新會(huì)話將被創(chuàng)建和保存。
如果有效的會(huì)話存在,其信息將被更新。每次更新時(shí),如果配置為這樣,會(huì)話ID可能會(huì)重新生成。
了解一旦初始化后,Session類自動(dòng)運(yùn)行對(duì)你來(lái)說(shuō)很重要。沒(méi)有什么你需要做的,導(dǎo)致上述行為發(fā)生。正如您將在下面看到的,您可以使用會(huì)話數(shù)據(jù),但讀取,寫(xiě)入和更新會(huì)話的過(guò)程是自動(dòng)的。
注意
在CLI下,會(huì)話庫(kù)將自動(dòng)停止,因?yàn)檫@是一個(gè)完全基于HTTP協(xié)議的概念。
除非你正在開(kāi)發(fā)一個(gè)AJAX用量很大的網(wǎng)站,否則你可以跳過(guò)這一節(jié)。但是,如果你是,而且如果你遇到性能問(wèn)題,那么這個(gè)筆記就是你正在尋找的東西。
以前版本的CodeIgniter中的會(huì)話沒(méi)有實(shí)現(xiàn)鎖定,這意味著使用同一會(huì)話的兩個(gè)HTTP請(qǐng)求可以同時(shí)運(yùn)行。要使用更合適的技術(shù)術(shù)語(yǔ) - 請(qǐng)求是非阻塞的。
但是,會(huì)話上下文中的非阻塞請(qǐng)求也意味著不安全,因?yàn)樵谝粋€(gè)請(qǐng)求中修改會(huì)話數(shù)據(jù)(或會(huì)話ID再生)可能會(huì)干擾第二個(gè)并發(fā)請(qǐng)求的執(zhí)行。這個(gè)細(xì)節(jié)是許多問(wèn)題的根源,也是CodeIgniter 3.0有一個(gè)完全重寫(xiě)的會(huì)話庫(kù)的主要原因。
我們?yōu)槭裁匆嬖V你這個(gè)?因?yàn)楹芸赡茉谡业叫阅軉?wèn)題的原因之后,可能會(huì)得出結(jié)論:鎖定是問(wèn)題,因此需要研究如何刪除鎖定...
不要那樣做!刪除鎖將是錯(cuò)誤的,它會(huì)導(dǎo)致更多的問(wèn)題!
鎖定不是問(wèn)題,它是一個(gè)解決方案。你的問(wèn)題是,你仍然打開(kāi)會(huì)議,而你已經(jīng)處理它,因此不再需要它。所以,你需要的是在你不再需要之后關(guān)閉當(dāng)前請(qǐng)求的會(huì)話。
長(zhǎng)話短說(shuō) - session_write_close()
一旦你不再需要任何與會(huì)話變量有關(guān)的事情,就會(huì)致電。
會(huì)話數(shù)據(jù)只是一個(gè)與特定會(huì)話ID(cookie)關(guān)聯(lián)的數(shù)組。
如果您以前在PHP中使用會(huì)話,則應(yīng)該熟悉PHP的$ _SESSION超全局(如果沒(méi)有,請(qǐng)閱讀該鏈接上的內(nèi)容)。
CodeIgniter通過(guò)相同的方式訪問(wèn)會(huì)話數(shù)據(jù),因?yàn)樗褂肞HP提供的會(huì)話處理器機(jī)制。使用會(huì)話數(shù)據(jù)與操作(讀取,設(shè)置和取消設(shè)置值)$_SESSION
數(shù)組一樣簡(jiǎn)單。
另外,CodeIgniter還提供了2種特殊類型的會(huì)話數(shù)據(jù),這些數(shù)據(jù)將在下面進(jìn)一步解釋:flashdata和tempdata。
注意
在以前的版本中,CodeIgniter中的常規(guī)會(huì)話數(shù)據(jù)被稱為'userdata'。請(qǐng)記住,如果該術(shù)語(yǔ)在手冊(cè)的其他地方使用。它的大部分內(nèi)容都是為了解釋自定義的'userdata'方法是如何工作的。
來(lái)自會(huì)話數(shù)組的任何信息都可以通過(guò)$_SESSION
超全局獲得:
$_SESSION['item']
或者通過(guò)魔術(shù)獲得者:
$this->session->item
為了向后兼容,通過(guò)以下userdata()
方法:
$this->session->userdata('item');
其中item是與您希望獲取的物品相對(duì)應(yīng)的數(shù)組鍵。例如,要將以前存儲(chǔ)的'名稱'項(xiàng)目分配給$name
變量,您將執(zhí)行以下操作:
$name = $_SESSION['name'];// or:$name = $this->session->name// or:$name = $this->session->userdata('name');
注意
userdata()
如果您嘗試訪問(wèn)的項(xiàng)目不存在,則該方法返回NULL。
如果你想檢索所有現(xiàn)有的用戶數(shù)據(jù),你可以簡(jiǎn)單地省略項(xiàng)目鍵(魔術(shù)獲得者只適用于屬性):
$_SESSION// or:$this->session->userdata();
比方說(shuō),一個(gè)特定的用戶登錄到您的網(wǎng)站。一旦通過(guò)身份驗(yàn)證,您就可以將他們的用戶名和電子郵件地址添加到會(huì)話中,使您可以在全球范圍內(nèi)使用這些數(shù)據(jù),而無(wú)需在需要時(shí)運(yùn)行數(shù)據(jù)庫(kù)查詢。
$_SESSION
與任何其他變量一樣,您可以簡(jiǎn)單地將數(shù)據(jù)分配給數(shù)組?;蜃鳛橐粋€(gè)屬性$this->session
。
或者,也可以使用將其分配為“用戶數(shù)據(jù)”的舊方法。但是,將包含新數(shù)據(jù)的數(shù)組傳遞給set_userdata()
方法:
$this->session->set_userdata($array);
$array
包含新數(shù)據(jù)的關(guān)聯(lián)數(shù)組在哪里?這是一個(gè)例子:
$newdata = array( 'username' => 'johndoe', 'email' => '[email protected]', 'logged_in' => TRUE);$this->session->set_userdata($newdata);
如果您想一次添加userdata一個(gè)值,set_userdata()
還支持以下語(yǔ)法:
$this->session->set_userdata('some_name', 'some_value');
如果您想驗(yàn)證會(huì)話值是否存在,只需檢查isset()
:
// returns FALSE if the 'some_name' item doesn't exist or is NULL,// TRUE otherwise:isset($_SESSION['some_name'])
或者你可以打電話給has_userdata()
:
$this->session->has_userdata('some_name');
正如其他任何變量一樣,$_SESSION
可以通過(guò)unset()
以下方式取消設(shè)置值:
unset($_SESSION['some_name']);// or multiple values:unset( $_SESSION['some_name'], $_SESSION['another_name']);
此外,正如set_userdata()
可以用來(lái)向會(huì)話添加信息一樣,unset_userdata()
可以通過(guò)傳遞會(huì)話密鑰來(lái)刪除它。例如,如果您想從會(huì)話數(shù)據(jù)數(shù)組中刪除'some_name':
$this->session->unset_userdata('some_name');
該方法還接受一組項(xiàng)目鍵以取消設(shè)置:
$array_items = array('username', 'email');$this->session->unset_userdata($array_items);
注意
在以前的版本中,該unset_userdata()
方法用于接受一個(gè)關(guān)聯(lián)數(shù)組key => 'dummy value'
對(duì)。這不再支持。
CodeIgniter支持“flashdata”或會(huì)話數(shù)據(jù),它們只會(huì)在下一個(gè)請(qǐng)求中使用,然后自動(dòng)清除。
這可能非常有用,特別是對(duì)于一次性信息,錯(cuò)誤或狀態(tài)消息(例如:“記錄2已刪除”)。
應(yīng)該注意的是,flashdata變量是常規(guī)會(huì)話變量,只有在'__ci_vars'鍵下以特定方式標(biāo)記(請(qǐng)不要觸摸那個(gè),你已被警告過(guò))。
將現(xiàn)有項(xiàng)目標(biāo)記為“flashdata”:
$this->session->mark_as_flash('item');
如果您想將多個(gè)項(xiàng)目標(biāo)記為flashdata,只需將密鑰作為數(shù)組傳遞即可:
$this->session->mark_as_flash(array('item', 'item2'));
添加flashdata:
$_SESSION['item'] = 'value';$this->session->mark_as_flash('item');
或者,使用該set_flashdata()
方法:
$this->session->set_flashdata('item', 'value');
You can also pass an array to set_flashdata()
, in the same manner as set_userdata()
.
讀取flashdata變量與讀取常規(guī)會(huì)話數(shù)據(jù)的過(guò)程相同$_SESSION
:
$_SESSION['item']
重要
該userdata()
方法不會(huì)返回flashdata項(xiàng)目。
但是,如果您想確定您正在閱讀“flashdata”(而不是其他類型),則還可以使用以下flashdata()
方法:
$this->session->flashdata('item');
或者為了獲得一個(gè)包含所有flash數(shù)據(jù)的數(shù)組,只需省略關(guān)鍵參數(shù):
$this->session->flashdata();
注意
flashdata()
如果無(wú)法找到該項(xiàng)目,該方法返回NULL。
如果您發(fā)現(xiàn)需要通過(guò)附加請(qǐng)求保留flashdata變量,則可以使用該keep_flashdata()
方法執(zhí)行此操作。您可以傳遞單個(gè)項(xiàng)目或一組flash數(shù)據(jù)項(xiàng)以保留。
$this->session->keep_flashdata('item');$this->session->keep_flashdata(array('item1', 'item2', 'item3'));
CodeIgniter also supports “tempdata”, or session data with a specific expiration time. After the value expires, or the session expires or is deleted, the value is automatically removed.
Similarly to flashdata, tempdata variables are regular session vars that are marked in a specific way under the ‘__ci_vars’ key (again, don’t touch that one).
To mark an existing item as “tempdata”, simply pass its key and expiry time (in seconds!) to the mark_as_temp()
method:
// 'item' will be erased after 300 seconds$this->session->mark_as_temp('item', 300);
You can mark multiple items as tempdata in two ways, depending on whether you want them all to have the same expiry time or not:
// Both 'item' and 'item2' will expire after 300 seconds$this->session->mark_as_temp(array('item', 'item2'), 300);// '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));
To add tempdata:
$_SESSION['item'] = 'value';$this->session->mark_as_temp('item', 300); // Expire in 5 minutes
Or alternatively, using the set_tempdata()
method:
$this->session->set_tempdata('item', 'value', 300);
You can also pass an array to set_tempdata()
:
$tempdata = array('newuser' => TRUE, 'message' => 'Thanks for joining!');$this->session->set_tempdata($tempdata, NULL, $expire);
Note
If the expiration is omitted or set to 0, the default time-to-live value of 300 seconds (or 5 minutes) will be used.
To read a tempdata variable, again you can just access it through the $_SESSION
superglobal array:
$_SESSION['item']
Important
The userdata()
method will NOT return tempdata items.
Or if you want to be sure that you’re reading “tempdata” (and not any other kind), you can also use the tempdata()
method:
$this->session->tempdata('item');
And of course, if you want to retrieve all existing tempdata:
$this->session->tempdata();
Note
The tempdata()
method returns NULL if the item cannot be found.
If you need to remove a tempdata value before it expires, you can directly unset it from the $_SESSION
array:
unset($_SESSION['item']);
However, this won’t remove the marker that makes this specific item to be tempdata (it will be invalidated on the next HTTP request), so if you intend to reuse that same key in the same request, you’d want to use unset_tempdata()
:
$this->session->unset_tempdata('item');
To clear the current session (for example, during a logout), you may simply use either PHP’s session_destroy() function, or the sess_destroy()
method. Both will work in exactly the same way:
session_destroy();// or$this->session->sess_destroy();
Note
This must be the last session-related operation that you do during the same request. All session data (including flashdata and tempdata) will be destroyed permanently and functions will be unusable during the same request after you destroy the session.
In previous CodeIgniter versions, the session data array included 4 items by default: ‘session_id’, ‘ip_address’, ‘user_agent’, ‘last_activity’.
This was due to the specifics of how sessions worked, but is now no longer necessary with our new implementation. However, it may happen that your application relied on these values, so here are alternative methods of accessing them:
session_id: session_id()
ip_address: $_SERVER['REMOTE_ADDR']
user_agent: $this->input->user_agent()
(unused by sessions)
last_activity: Depends on the storage, no straightforward way. Sorry!
CodeIgniter will usually make everything work out of the box. However, Sessions are a very sensitive component of any application, so some careful configuration must be done. Please take your time to consider all of the options and their effects.
You’ll find the following Session related preferences in your application/config/config.php file:
Preference | Default | Options | Description |
---|---|---|---|
sess_driver | files | files/database/redis/memcached/custom | The session storage driver to use. |
sess_cookie_name | ci_session | A-Za-z_- characters only | The name used for the session cookie. |
sess_expiration | 7200 (2 hours) | Time in seconds (integer) | The number of seconds you would like the session to last. If you would like a non-expiring session (until browser is closed) set the value to zero: 0 |
sess_save_path | NULL | None | Specifies the storage location, depends on the driver being used. |
sess_match_ip | FALSE | TRUE/FALSE (boolean) | Whether to validate the user’s IP address when reading the session cookie. Note that some ISPs dynamically changes the IP, so if you want a non-expiring session you will likely set this to FALSE. |
sess_time_to_update | 300 | Time in seconds (integer) | This option controls how often the session class will regenerate itself and create a new session ID. Setting it to 0 will disable session ID regeneration. |
sess_regenerate_destroy | FALSE | TRUE/FALSE (boolean) | Whether to destroy session data associated with the old session ID when auto-regenerating the session ID. When set to FALSE, the data will be later deleted by the garbage collector. |
Note
As a last resort, the Session library will try to fetch PHP’s session related INI settings, as well as legacy CI settings such as ‘sess_expire_on_close’ when any of the above is not configured. However, you should never rely on this behavior as it can cause unexpected results or be changed in the future. Please configure everything properly.
In addition to the values above, the cookie and native drivers apply the following configuration values shared by the Input and Security classes:
Preference | Default | Description |
---|---|---|
cookie_domain | ‘’ | The domain for which the session is applicable |
cookie_path | / | The path to which the session is applicable |
cookie_secure | FALSE | Whether to create the session cookie only on encrypted (HTTPS) connections |
Note
The ‘cookie_httponly’ setting doesn’t have an effect on sessions. Instead the HttpOnly parameter is always enabled, for security reasons. Additionally, the ‘cookie_prefix’ setting is completely ignored.
As already mentioned, the Session library comes with 4 drivers, or storage engines, that you can use:
files
database
redis
memcached
By default, the Files Driver will be used when a session is initialized, because it is the most safe choice and is expected to work everywhere (virtually every environment has a file system).
However, any other driver may be selected via the $config['sess_driver']
line in your application/config/config.php file, if you chose to do so. Have it in mind though, every driver has different caveats, so be sure to get yourself familiar with them (below) before you make that choice.
In addition, you may also create and use Custom Drivers, if the ones provided by default don’t satisfy your use case.
Note
In previous CodeIgniter versions, a different, “cookie driver” was the only option and we have received negative feedback on not providing that option. While we do listen to feedback from the community, we want to warn you that it was dropped because it is unsafe and we advise you NOT to try to replicate it via a custom driver.
The ‘files’ driver uses your file system for storing session data.
It can safely be said that it works exactly like PHP’s own default session implementation, but in case this is an important detail for you, have it mind that it is in fact not the same code and it has some limitations (and advantages).
To be more specific, it doesn’t support PHP’s directory level and mode formats used in session.save_path, and it has most of the options hard-coded for safety. Instead, only absolute paths are supported for $config['sess_save_path']
.
Another important thing that you should know, is to make sure that you don’t use a publicly-readable or shared directory for storing your session files. Make sure that only you have access to see the contents of your chosen sess_save_path directory. Otherwise, anybody who can do that, can also steal any of the current sessions (also known as “session fixation” attack).
On UNIX-like operating systems, this is usually achieved by setting the 0700 mode permissions on that directory via the chmod
command, which allows only the directory’s owner to perform read and write operations on it. But be careful because the system user running the script is usually not your own, but something like ‘www-data’ instead, so only setting those permissions will probable break your application.
Instead, you should do something like this, depending on your environment
mkdir /<path to your application directory>/sessions/chmod 0700 /<path to your application directory>/sessions/chown www-data /<path to your application directory>/sessions/
Some of you will probably opt to choose another session driver because file storage is usually slower. This is only half true.
A very basic test will probably trick you into believing that an SQL database is faster, but in 99% of the cases, this is only true while you only have a few current sessions. As the sessions count and server loads increase - which is the time when it matters - the file system will consistently outperform almost all relational database setups.
In addition, if performance is your only concern, you may want to look into using tmpfs, (warning: external resource), which can make your sessions blazing fast.
The ‘database’ driver uses a relational database such as MySQL or PostgreSQL to store sessions. This is a popular choice among many users, because it allows the developer easy access to the session data within an application - it is just another table in your database.
However, there are some conditions that must be met:
Only your default database connection (or the one that you access as $this->db
from your controllers) can be used.
You must have the Query Builder enabled.
You can NOT use a persistent connection.
You can NOT use a connection with the cache_on setting enabled.
In order to use the ‘database’ session driver, you must also create this table that we already mentioned and then set it as your $config['sess_save_path']
value. For example, if you would like to use ‘ci_sessions’ as your table name, you would do this:
$config['sess_driver'] = 'database';$config['sess_save_path'] = 'ci_sessions';
Note
If you’ve upgraded from a previous version of CodeIgniter and you don’t have ‘sess_save_path’ configured, then the Session library will look for the old ‘sess_table_name’ setting and use it instead. Please don’t rely on this behavior as it will get removed in the future.
And then of course, create the database table ...
For MySQL:
CREATE TABLE IF NOT EXISTS `ci_sessions` ( `id` varchar(128) NOT NULL, `ip_address` varchar(45) NOT NULL, `timestamp` int(10) unsigned DEFAULT 0 NOT NULL, `data` blob NOT NULL, KEY `ci_sessions_timestamp` (`timestamp`));
For PostgreSQL:
CREATE TABLE "ci_sessions" ( "id" varchar(128) NOT NULL, "ip_address" varchar(45) NOT NULL, "timestamp" bigint DEFAULT 0 NOT NULL, "data" text DEFAULT '' NOT NULL);CREATE INDEX "ci_sessions_timestamp" ON "ci_sessions" ("timestamp");
You will also need to add a PRIMARY KEY depending on your ‘sess_match_ip’ setting. The examples below work both on MySQL and PostgreSQL:
// When sess_match_ip = TRUEALTER TABLE ci_sessions ADD PRIMARY KEY (id, ip_address);// When sess_match_ip = FALSEALTER TABLE ci_sessions ADD PRIMARY KEY (id);// To drop a previously created primary key (use when changing the setting)ALTER TABLE ci_sessions DROP PRIMARY KEY;
Important
Only MySQL and PostgreSQL databases are officially supported, due to lack of advisory locking mechanisms on other platforms. Using sessions without locks can cause all sorts of problems, especially with heavy usage of AJAX, and we will not support such cases. Use session_write_close()
after you’ve done processing session data if you’re having performance issues.
Note
Since Redis doesn’t have a locking mechanism exposed, locks for this driver are emulated by a separate value that is kept for up to 300 seconds.
Redis is a storage engine typically used for caching and popular because of its high performance, which is also probably your reason to use the ‘redis’ session driver.
The downside is that it is not as ubiquitous as relational databases and requires the phpredis PHP extension to be installed on your system, and that one doesn’t come bundled with PHP. Chances are, you’re only be using the ‘redis’ driver only if you’re already both familiar with Redis and using it for other purposes.
Just as with the ‘files’ and ‘database’ drivers, you must also configure the storage location for your sessions via the $config['sess_save_path']
setting. The format here is a bit different and complicated at the same time. It is best explained by the phpredis extension’s README file, so we’ll simply link you to it:
https://github.com/phpredis/phpredis#php-session-handler
Warning
CodeIgniter’s Session library does NOT use the actual ‘redis’ session.save_handler
. Take note only of the path format in the link above.
For the most common case however, a simple host:port
pair should be sufficient:
$config['sess_driver'] = 'redis';$config['sess_save_path'] = 'tcp://localhost:6379';
Note
Since Memcache doesn’t have a locking mechanism exposed, locks for this driver are emulated by a separate value that is kept for up to 300 seconds.
The ‘memcached’ driver is very similar to the ‘redis’ one in all of its properties, except perhaps for availability, because PHP’s Memcached extension is distributed via PECL and some Linux distrubutions make it available as an easy to install package.
Other than that, and without any intentional bias towards Redis, there’s not much different to be said about Memcached - it is also a popular product that is usually used for caching and famed for its speed.
However, it is worth noting that the only guarantee given by Memcached is that setting value X to expire after Y seconds will result in it being deleted after Y seconds have passed (but not necessarily that it won’t expire earlier than that time). This happens very rarely, but should be considered as it may result in loss of sessions.
The $config['sess_save_path']
format is fairly straightforward here, being just a host:port
pair:
$config['sess_driver'] = 'memcached';$config['sess_save_path'] = 'localhost:11211';
Multi-server configuration with an optional weight parameter as the third colon-separated (:weight
) value is also supported, but we have to note that we haven’t tested if that is reliable.
If you want to experiment with this feature (on your own risk), simply separate the multiple server paths with commas:
// localhost will be given higher priority (5) here,// compared to 192.0.2.1 with a weight of 1.$config['sess_save_path'] = 'localhost:11211:5,192.0.2.1:11211:1';
You may also create your own, custom session drivers. However, have it in mind that this is typically not an easy task, as it takes a lot of knowledge to do it properly.
You need to know not only how sessions work in general, but also how they work specifically in PHP, how the underlying storage mechanism works, how to handle concurrency, avoid deadlocks (but NOT through lack of locks) and last but not least - how to handle the potential security issues, which is far from trivial.
Long story short - if you don’t know how to do that already in raw PHP, you shouldn’t be trying to do it within CodeIgniter either. You’ve been warned.
If you only want to add some extra functionality to your sessions, just extend the base Session class, which is a lot more easier. Read the Creating Libraries article to learn how to do that.
Now, to the point - there are three general rules that you must follow when creating a session driver for CodeIgniter:
Put your driver’s file under application/libraries/Session/drivers/ and follow the naming conventions used by the Session class.
For example, if you were to create a ‘dummy’ driver, you would have a Session_dummy_driver
class name, that is declared in application/libraries/Session/drivers/Session_dummy_driver.php.
Extend the CI_Session_driver
class.
This is just a basic class with a few internal helper methods. It is also extendable like any other library, if you really need to do that, but we are not going to explain how ... if you’re familiar with how class extensions/overrides work in CI, then you already know how to do it. If not, well, you shouldn’t be doing it in the first place.
Implement the SessionHandlerInterface interface.
Note
You may notice that SessionHandlerInterface
is provided by PHP since version 5.4.0. CodeIgniter will automatically declare the same interface if you’re running an older PHP version.
The link will explain why and how.
So, based on our ‘dummy’ driver example above, you’d end up with something like this:
// application/libraries/Session/drivers/Session_dummy_driver.php:class CI_Session_dummy_driver extends CI_Session_driver implements SessionHandlerInterface{ public function __construct(&$params) { // DO NOT forget this parent::__construct($params); // Configuration & other initializations } public function open($save_path, $name) { // Initialize storage mechanism (connection) } public function read($session_id) { // Read session data (if exists), acquire locks } public function write($session_id, $session_data) { // Create / update session data (it might not exist!) } public function close() { // Free locks, close connections / streams / etc. } public function destroy($session_id) { // Call close() method & destroy data for current session (order may differ) } public function gc($maxlifetime) { // Erase data for expired sessions }}
If you’ve done everything properly, you can now set your sess_driver configuration value to ‘dummy’ and use your own driver. Congratulations!
class CI_Sessionuserdata([$key = NULL])
Parameters: | $key (mixed) – Session item key or NULL |
---|---|
Returns: | Value of the specified item key, or an array of all userdata |
Return type: | mixed |
$key (mixed) – Session item key or NULL
Returns: Value of the specified item key, or an array of all userdata
Return type: mixed
Gets the value for a specific `$_SESSION` item, or an array of all “userdata” items if not key was specified.
Note
This is a legacy method kept only for backwards compatibility with older applications. You should directly access $_SESSION
instead.
all_userdata()
Returns: | An array of all userdata |
---|---|
Return type: | array |
&get_userdata()
Returns: | A reference to $_SESSION |
---|---|
Return type: | array |
has_userdata($key)
Parameters: | $key (string) – Session item key |
---|---|
Returns: | TRUE if the specified key exists, FALSE if not |
Return type: | bool |
$key (string) – Session item key
Returns: TRUE if the specified key exists, FALSE if not
Return type: bool
Checks if an item exists in `$_SESSION`.
Note
This is a legacy method kept only for backwards compatibility with older applications. It is just an alias for isset($_SESSION[$key])
- please use that instead.
set_userdata($data[, $value = NULL])
Parameters: | $data (mixed) – An array of key/value pairs to set as session data, or the key for a single item $value (mixed) – The value to set for a specific session item, if $data is a key |
---|---|
Return type: | void |
$data (mixed) – An array of key/value pairs to set as session data, or the key for a single item
$value (mixed) – The value to set for a specific session item, if $data is a key
Return type: void
Assigns data to the `$_SESSION` superglobal.
Note
This is a legacy method kept only for backwards compatibility with older applications.
unset_userdata($key)
Parameters: | $key (mixed) – Key for the session data item to unset, or an array of multiple keys |
---|---|
Return type: | void |
$key (mixed) – Key for the session data item to unset, or an array of multiple keys
Return type: void
Unsets the specified key(s) from the `$_SESSION` superglobal.
Note
This is a legacy method kept only for backwards compatibility with older applications. It is just an alias for unset($_SESSION[$key])
- please use that instead.
mark_as_flash($key)
Parameters: | $key (mixed) – Key to mark as flashdata, or an array of multiple keys |
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
$key (mixed) – Key to mark as flashdata, or an array of multiple keys
Returns: TRUE on success, FALSE on failure
Return type: bool
Marks a `$_SESSION` item key (or multiple ones) as “flashdata”.
get_flash_keys()
Returns: | Array containing the keys of all “flashdata” items. |
---|---|
Return type: | array |
unmark_flash($key)
Parameters: | $key (mixed) – Key to be un-marked as flashdata, or an array of multiple keys |
---|---|
Return type: | void |
$key (mixed) – Key to be un-marked as flashdata, or an array of multiple keys
Return type: void
Unmarks a `$_SESSION` item key (or multiple ones) as “flashdata”.
flashdata([$key = NULL])
Parameters: | $key (mixed) – Flashdata item key or NULL |
---|---|
Returns: | Value of the specified item key, or an array of all flashdata |
Return type: | mixed |
$key (mixed) – Flashdata item key or NULL
Returns: Value of the specified item key, or an array of all flashdata
Return type: mixed
Gets the value for a specific `$_SESSION` item that has been marked as “flashdata”, or an array of all “flashdata” items if no key was specified.
Note
This is a legacy method kept only for backwards compatibility with older applications. You should directly access $_SESSION
instead.
keep_flashdata($key)
Parameters: | $key (mixed) – Flashdata key to keep, or an array of multiple keys |
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
$key (mixed) – Flashdata key to keep, or an array of multiple keys
Returns: TRUE on success, FALSE on failure
Return type: bool
Retains the specified session data key(s) as “flashdata” through the next request.
Note
This is a legacy method kept only for backwards compatibility with older applications. It is just an alias for the mark_as_flash()
method.
set_flashdata($data[, $value = NULL])
Parameters: | $data (mixed) – An array of key/value pairs to set as flashdata, or the key for a single item $value (mixed) – The value to set for a specific session item, if $data is a key |
---|---|
Return type: | void |
$data (mixed) – An array of key/value pairs to set as flashdata, or the key for a single item
$value (mixed) – The value to set for a specific session item, if $data is a key
Return type: void
Assigns data to the `$_SESSION` superglobal and marks it as “flashdata”.
Note
This is a legacy method kept only for backwards compatibility with older applications.
mark_as_temp($key[, $ttl = 300])
Parameters: | $key (mixed) – Key to mark as tempdata, or an array of multiple keys $ttl (int) – Time-to-live value for the tempdata, in seconds |
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
$key (mixed) – Key to mark as tempdata, or an array of multiple keys
$ttl (int) – Time-to-live value for the tempdata, in seconds
Returns: TRUE on success, FALSE on failure
Return type: bool
Marks a `$_SESSION` item key (or multiple ones) as “tempdata”.
get_temp_keys()
Returns: | Array containing the keys of all “tempdata” items. |
---|---|
Return type: | array |
unmark_temp($key)
Parameters: | $key (mixed) – Key to be un-marked as tempdata, or an array of multiple keys |
---|---|
Return type: | void |
$key (mixed) – Key to be un-marked as tempdata, or an array of multiple keys
Return type: void
Unmarks a `$_SESSION` item key (or multiple ones) as “tempdata”.
tempdata([$key = NULL])
Parameters: | $key (mixed) – Tempdata item key or NULL |
---|---|
Returns: | Value of the specified item key, or an array of all tempdata |
Return type: | mixed |
$key (mixed) – Tempdata item key or NULL
Returns: Value of the specified item key, or an array of all tempdata
Return type: mixed
Gets the value for a specific `$_SESSION` item that has been marked as “tempdata”, or an array of all “tempdata” items if no key was specified.
Note
This is a legacy method kept only for backwards compatibility with older applications. You should directly access $_SESSION
instead.
set_tempdata($data[, $value = NULL])
Parameters: | $data (mixed) – An array of key/value pairs to set as tempdata, or the key for a single item $value (mixed) – The value to set for a specific session item, if $data is a key $ttl (int) – Time-to-live value for the tempdata item(s), in seconds |
---|---|
Return type: | void |
$data (mixed) – An array of key/value pairs to set as tempdata, or the key for a single item
$value (mixed) – The value to set for a specific session item, if $data is a key
$ttl (int) – Time-to-live value for the tempdata item(s), in seconds
Return type: void
Assigns data to the `$_SESSION` superglobal and marks it as “tempdata”.
Note
This is a legacy method kept only for backwards compatibility with older applications.
sess_regenerate([$destroy = FALSE])
Parameters: | $destroy (bool) – Whether to destroy session data |
---|---|
Return type: | void |
$destroy (bool) – Whether to destroy session data
Return type: void
Regenerate session ID, optionally destroying the current session’s data.
Note
This method is just an alias for PHP’s native session_regenerate_id() function.
sess_destroy()
Return type: | void |
---|
__get($key)
Parameters: | $key (string) – Session item key |
---|---|
Returns: | The requested session data item, or NULL if it doesn’t exist |
Return type: | mixed |
$key (string) – Session item key
Returns: The requested session data item, or NULL if it doesn’t exist
Return type: mixed
A magic method that allows you to use `$this->session->item` instead of `$_SESSION['item']`, if that’s what you prefer.
It will also return the session ID by calling session_id()
if you try to access $this->session->session_id
.
__set($key, $value)
Parameters: | $key (string) – Session item key $value (mixed) – Value to assign to the session item key |
---|---|
Returns: | void |
$key (string) – Session item key
$value (mixed) – Value to assign to the session item key
Returns: void
A magic method that allows you to assign items to `$_SESSION` by accessing them as `$this->session` properties:
$this->session->foo = 'bar'; // Results in: // $_SESSION'foo' = 'bar';
? 2014–2017 British Columbia Institute of Technology
Licensed under the MIT License.
https://www.codeigniter.com/user_guide/libraries/sessions.html