summaryrefslogtreecommitdiffstats
path: root/user_guide_src
diff options
context:
space:
mode:
Diffstat (limited to 'user_guide_src')
-rw-r--r--user_guide_src/source/_themes/eldocs/layout.html16
-rw-r--r--user_guide_src/source/_themes/eldocs/searchbox.html21
-rw-r--r--user_guide_src/source/_themes/eldocs/static/asset/css/common.css6
-rw-r--r--user_guide_src/source/changelog.rst30
-rw-r--r--user_guide_src/source/conf.py1
-rw-r--r--user_guide_src/source/database/configuration.rst7
-rw-r--r--user_guide_src/source/index.rst3
-rw-r--r--user_guide_src/source/installation/upgrade_300.rst27
-rw-r--r--user_guide_src/source/libraries/form_validation.rst1
-rw-r--r--user_guide_src/source/libraries/loader.rst71
-rw-r--r--user_guide_src/source/libraries/migration.rst134
-rw-r--r--user_guide_src/source/libraries/sessions.rst338
12 files changed, 547 insertions, 108 deletions
diff --git a/user_guide_src/source/_themes/eldocs/layout.html b/user_guide_src/source/_themes/eldocs/layout.html
index 01db07cac..51d61b849 100644
--- a/user_guide_src/source/_themes/eldocs/layout.html
+++ b/user_guide_src/source/_themes/eldocs/layout.html
@@ -91,13 +91,7 @@
</div><!-- /#brand -->
<div id="header">
- <form method="get" action="http://www.google.com/search">
- <fieldset>
- <input type="text" name="q" id="q" value="">
- <input type="hidden" name="as_sitesearch" id="as_sitesearch" value="{{ project_domain }}/user_guide/" />
- <input class="grades" type="submit" value="search">
- </fieldset>
- </form>
+ {%- include "searchbox.html" %}
<ul>
{%- block rootrellink %}
<li><a href="{{ pathto(master_doc) }}">User Guide Home</a>{%- if pagename != 'index' %}&nbsp;&nbsp;{{ reldelim1 }}{%- endif %}</li>
@@ -113,8 +107,10 @@
</ul>
</div><!-- /#header -->
- <div class="section" id="content">
+ <div class="section body" id="content">
+ {%- block body %}
{{ body }}
+ {%- endblock %}
</div>
{%- endblock %}
@@ -125,8 +121,8 @@
{%- block footer %}
<div id="footer">
<p class="top"><a href="#header" title="Return to top">Return to top</a></p>
- <p><a href="{{ project_url }}">{{ project }}</a> &ndash; Copyright &copy; {{ copyright }}</a></p>
+ <p><a href="http://{{ project_domain }}/">{{ project }}</a> &ndash; Copyright &copy; {{ copyright }}</a></p>
</div><!-- /#footer -->
{%- endblock %}
</body>
-</html>
+</html> \ No newline at end of file
diff --git a/user_guide_src/source/_themes/eldocs/searchbox.html b/user_guide_src/source/_themes/eldocs/searchbox.html
new file mode 100644
index 000000000..039590bd9
--- /dev/null
+++ b/user_guide_src/source/_themes/eldocs/searchbox.html
@@ -0,0 +1,21 @@
+<!--
+ --------------------------------
+ Original Google search box block
+ --------------------------------
+
+<form method="get" action="http://www.google.com/search">
+ <fieldset>
+ <input type="text" name="q" id="q" value="">
+ <input type="hidden" name="as_sitesearch" id="as_sitesearch" value="{{ project_domain }}/user_guide/" />
+ <input class="grades" type="submit" value="search">
+ </fieldset>
+</form>
+-->
+
+
+<form class="search" action="{{ pathto('search') }}" method="get">
+ <input type="text" name="q" id="q" value="" />
+ <input type="submit" value="search" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+</form>
diff --git a/user_guide_src/source/_themes/eldocs/static/asset/css/common.css b/user_guide_src/source/_themes/eldocs/static/asset/css/common.css
index 6cabda037..0a63871c5 100644
--- a/user_guide_src/source/_themes/eldocs/static/asset/css/common.css
+++ b/user_guide_src/source/_themes/eldocs/static/asset/css/common.css
@@ -148,6 +148,8 @@ fieldset{ border: 0; }
.top{ float: right; }
+.highlight{ overflow-x: auto; }
+
.admonition,
.highlight-ee,
.highlight-ci,
@@ -166,6 +168,8 @@ fieldset{ border: 0; }
padding: 10px 10px 8px;
}
+.highlight-ci{ background-color: #FEFEFE; border-color: #E5E5E5; }
+
.admonition p{ margin: 0; }
.codeblock{ margin: 10px 0; }
@@ -181,6 +185,8 @@ fieldset{ border: 0; }
}
.admonition-title:after{ content: ': '; }
+
+.highlighted{ background-color: #FFF09B; }
#table-contents{
bottom: 0;
diff --git a/user_guide_src/source/changelog.rst b/user_guide_src/source/changelog.rst
index cf0d29f1b..0835a9c01 100644
--- a/user_guide_src/source/changelog.rst
+++ b/user_guide_src/source/changelog.rst
@@ -34,6 +34,7 @@ Release Date: Not Released
- Added support for rar archives to mimes.php.
- Updated support for xml ('application/xml') and xsl ('application/xml', 'text/xsl') files in mimes.php.
- Updated support for doc files in mimes.php.
+ - Updated support for docx files in mimes.php.
- Updated support for php files in mimes.php.
- Updated support for zip files in mimes.php.
- Updated support for csv files in mimes.php.
@@ -140,14 +141,28 @@ Release Date: Not Released
- Added PDO support for create_database(), drop_database and drop_table() in :doc:`Database Forge <database/forge>`.
- Added unbuffered_row() method for getting a row without prefetching whole result (consume less memory).
- Added PDO support for ``list_fields()`` in :doc:`Database Results <database/results>`.
- - Added capability for packages to hold database.php config files
+ - Added capability for packages to hold database.php config files
- Added subdrivers support (currently only used by PDO).
+ - Added client compression support for MySQL and MySQLi.
+ - Removed Loader class from Database error to better find the likely culprit.
- Libraries
- - CI_Session now respects php.ini's session.gc_probability and session.gc_divisor
+ - :doc:`Session Library <libraries/sessions>` changes include:
+ - Library changed to :doc:`Driver <general/drivers>` with classic Cookie driver as default.
+ - Added Native PHP Session driver to work with $_SESSION.
+ - Custom session drivers can be added anywhere in package paths and loaded with Session library.
+ - Session drivers interchangeable on the fly.
+ - New tempdata feature allows setting user data items with an expiration time.
+ - Added default $config['sess_driver'] and $config['sess_valid_drivers'] items to config.php file.
+ - Cookie driver now respects php.ini's session.gc_probability and session.gc_divisor
+ - Changed the Cookie driver to select only one row when using database sessions.
+ - Cookie driver now only writes to database at end of request when using database.
+ - Cookie driver now uses PHP functions for faster array manipulation when using database.
+ - Added all_flashdata() method to session class. Returns an associative array of only flashdata.
+ - Added has_userdata() method to verify existence of userdata item.
+ - Added tempdata(), set_tempdata(), and unset_tempdata() methods for manipulating tempdata.
- Added max_filename_increment config setting for Upload library.
- - CI_Loader::_ci_autoloader() is now a protected method.
- :doc:`Cart library <libraries/cart>` changes include:
- It now auto-increments quantity's instead of just resetting it, this is the default behaviour of large e-commerce sites.
- Product Name strictness can be disabled via the Cart Library by switching "$product_name_safe".
@@ -171,8 +186,6 @@ Release Date: Not Released
- Native PHP functions used as rules can now accept an additional parameter, other than the data itself.
- Updated set_rules() to accept an array of rules as well as a string.
- Fields that have empty rules set no longer run through validation (and therefore are not considered erroneous).
- - Changed the :doc:`Session Library <libraries/sessions>` to select only one row when using database sessions.
- - Added all_flashdata() method to session class. Returns an associative array of only flashdata.
- Allowed for setting table class defaults in a config file.
- Added a Wincache driver to the :doc:`Caching Library <libraries/caching>`.
- Added a Redis driver to the :doc:`Caching Library <libraries/caching>`.
@@ -194,7 +207,11 @@ Release Date: Not Released
- Changed private methods in the :doc:`URI Library <libraries/uri>` to protected so MY_URI can override them.
- Removed CI_CORE boolean constant from CodeIgniter.php (no longer Reactor and Core versions).
- - Added method get_vars() to the :doc:`Loader Library <libraries/loader>` to retrieve all variables loaded with $this->load->vars().
+ - :doc:`Loader Library <libraries/loader>` changes include:
+ - Added method get_vars() to the Loader to retrieve all variables loaded with $this->load->vars().
+ - CI_Loader::_ci_autoloader() is now a protected method.
+ - Added autoloading of drivers with $autoload['drivers'].
+ - CI_Loader::library() will now load drivers as well, for backward compatibility of converted libraries (like Session).
- is_loaded() function from system/core/Commons.php now returns a reference.
- $config['rewrite_short_tags'] now has no effect when using PHP 5.4 as *<?=* will always be available.
- Added method() to the :doc:`Input Library <libraries/input>` to retrieve $_SERVER['REQUEST_METHOD'].
@@ -322,6 +339,7 @@ Bug fixes for 3.0
- Fixed a bug (#1613) - :doc:`Form Helper <helpers/form_helper>` functions ``form_multiselect()``, ``form_dropdown()`` didn't properly handle empty array option groups.
- Fixed a bug (#1605) - :doc:`Pagination Library <libraries/pagination>` produced incorrect *previous* and *next* link values.
- Fixed a bug in SQLSRV's ``affected_rows()`` method where an erroneous function name was used.
+- Fixed a bug (#1000) - Change syntax of $view_file to $_ci_view_file to prevent being overwritten by application.
Version 2.1.2
=============
diff --git a/user_guide_src/source/conf.py b/user_guide_src/source/conf.py
index e972a388b..f68405b36 100644
--- a/user_guide_src/source/conf.py
+++ b/user_guide_src/source/conf.py
@@ -167,6 +167,7 @@ html_last_updated_fmt = '%b %d, %Y'
# Output file base name for HTML help builder.
htmlhelp_basename = 'CodeIgniterdoc'
+html_copy_source = False
# -- Options for LaTeX output --------------------------------------------------
diff --git a/user_guide_src/source/database/configuration.rst b/user_guide_src/source/database/configuration.rst
index c17de600a..636b5b5b2 100644
--- a/user_guide_src/source/database/configuration.rst
+++ b/user_guide_src/source/database/configuration.rst
@@ -28,6 +28,7 @@ prototype::
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
+ 'compress' => TRUE,
'stricton' => FALSE,
'failover' => array()
);
@@ -69,6 +70,7 @@ These failovers can be specified by setting the failover for a connection like t
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
+ 'compress' => TRUE,
'stricton' => FALSE
),
array(
@@ -86,6 +88,7 @@ These failovers can be specified by setting the failover for a connection like t
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
+ 'compress' => TRUE,
'stricton' => FALSE
)
);
@@ -115,6 +118,7 @@ example, to set up a "test" environment you would do this::
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
+ 'compress' => TRUE,
'stricton' => FALSE,
'failover' => array()
);
@@ -174,11 +178,12 @@ Explanation of Values:
customizable by the end user.
**autoinit** Whether or not to automatically connect to the database when the library loads. If set to false,
the connection will take place prior to executing the first query.
+**compress** Whether or not to use client compression for MySQL or MySQLi.
**stricton** TRUE/FALSE (boolean) - Whether to force "Strict Mode" connections, good for ensuring strict SQL
while developing an application.
**port** The database port number. To use this value you have to add a line to the database config array.
::
-
+
$db['default']['port'] = 5432;
====================== ==================================================================================================
diff --git a/user_guide_src/source/index.rst b/user_guide_src/source/index.rst
index e42425bab..35089703f 100644
--- a/user_guide_src/source/index.rst
+++ b/user_guide_src/source/index.rst
@@ -80,6 +80,7 @@ Driver Reference
- :doc:`libraries/caching`
- :doc:`database/index`
- :doc:`libraries/javascript`
+- :doc:`libraries/sessions`
****************
Helper Reference
@@ -119,4 +120,4 @@ Contributing to CodeIgniter
documentation/index
tutorial/index
general/quick_reference
- general/credits \ No newline at end of file
+ general/credits
diff --git a/user_guide_src/source/installation/upgrade_300.rst b/user_guide_src/source/installation/upgrade_300.rst
index f3a637326..31a5c0761 100644
--- a/user_guide_src/source/installation/upgrade_300.rst
+++ b/user_guide_src/source/installation/upgrade_300.rst
@@ -31,8 +31,24 @@ Step 3: Remove $autoload['core'] from your config/autoload.php
Use of the ``$autoload['core']`` config array has been deprecated as of CodeIgniter 1.4.1 and is now removed.
Move any entries that you might have listed there to ``$autoload['libraries']`` instead.
+**************************************************************
+Step 4: Add new session driver items to your config/config.php
+**************************************************************
+
+With the change from a single Session Library to the new Session Driver, two new config items have been added:
+
+ - ``$config['sess_driver']`` selects which driver to initially load. Options are:
+ - 'cookie' (the default) for classic CodeIgniter cookie-based sessions
+ - 'native' for native PHP Session support
+ - the name of a custom driver you have provided (see :doc:`Session Driver <../libraries/sessions>` for more info)
+ - ``$config['sess_valid_drivers']`` provides an array of additional custom drivers to make available for loading
+
+As the new Session Driver library loads the classic Cookie driver by default and always makes 'cookie' and 'native'
+available as valid drivers, neither of these configuration items are required. However, it is recommended that you
+add them for clarity and ease of configuration in the future.
+
***************************************
-Step 4: Update your config/database.php
+Step 5: Update your config/database.php
***************************************
Due to 3.0.0's renaming of Active Record to Query Builder, inside your `config/database.php`, you will
@@ -43,20 +59,20 @@ need to rename the `$active_record` variable to `$query_builder`.
$query_builder = TRUE;
*******************************
-Step 5: Move your errors folder
+Step 6: Move your errors folder
*******************************
In version 3.0.0, the errors folder has been moved from _application/errors* to _application/views/errors*.
****************************************************************************
-Step 6: Check the calls to Array Helper's element() and elements() functions
+Step 7: Check the calls to Array Helper's element() and elements() functions
****************************************************************************
The default return value of these functions, when the required elements
don't exist, has been changed from FALSE to NULL.
***************************************************************
-Step 7: Remove usage of (previously) deprecated functionalities
+Step 8: Remove usage of (previously) deprecated functionalities
***************************************************************
In addition to the ``$autoload['core']`` configuration setting, there's a number of other functionalities
@@ -147,7 +163,8 @@ The :doc:`Email library <../libraries/email>` will automatically clear the set p
emails. To override this behaviour, pass FALSE as the first parameter in the ``send()`` function:
::
+
if ($this->email->send(FALSE))
{
// Parameters won't be cleared
- } \ No newline at end of file
+ }
diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst
index 3bcad7ba6..39f787402 100644
--- a/user_guide_src/source/libraries/form_validation.rst
+++ b/user_guide_src/source/libraries/form_validation.rst
@@ -884,7 +884,6 @@ Rule Parameter Description
0, 1, 2, 3, etc.
**is_natural_no_zero** No Returns FALSE if the form element contains anything other than a natural
number, but not zero: 1, 2, 3, etc.
-**is_unique** Yes Returns FALSE if the form element is not unique in a database table. is_unique[table.field]
**valid_email** No Returns FALSE if the form element does not contain a valid email address.
**valid_emails** No Returns FALSE if any value provided in a comma separated list is not a valid email.
**valid_ip** No Returns FALSE if the supplied IP is not valid.
diff --git a/user_guide_src/source/libraries/loader.rst b/user_guide_src/source/libraries/loader.rst
index aadf9740a..33c1bafec 100644
--- a/user_guide_src/source/libraries/loader.rst
+++ b/user_guide_src/source/libraries/loader.rst
@@ -4,6 +4,7 @@ Loader Class
Loader, as the name suggests, is used to load elements. These elements
can be libraries (classes) :doc:`View files <../general/views>`,
+:doc:`Drivers <../general/drivers>`,
:doc:`Helpers <../general/helpers>`,
:doc:`Models <../general/models>`, or your own files.
@@ -74,6 +75,70 @@ Assigning a Library to a different object name
If the third (optional) parameter is blank, the library will usually be
assigned to an object with the same name as the library. For example, if
+the library is named Calendar, it will be assigned to a variable named
+$this->calendar.
+
+If you prefer to set your own class names you can pass its value to the
+third parameter::
+
+ $this->load->library('calendar', '', 'my_calendar');
+
+ // Calendar class is now accessed using:
+
+ $this->my_calendar
+
+Please take note, when multiple libraries are supplied in an array for
+the first parameter, this parameter is discarded.
+
+$this->load->driver('parent_name', $config, 'object name')
+===========================================================
+
+This function is used to load driver libraries. Where parent_name is the
+name of the parent class you want to load.
+
+As an example, if you would like to use sessions with CodeIgniter, the first
+step is to load the session driver within your controller::
+
+ $this->load->driver('session');
+
+Once loaded, the library will be ready for use, using
+$this->session->*some_function*().
+
+Driver files must be stored in a subdirectory within the main
+"libraries" folder, or within your personal application/libraries
+folder. The subdirectory must match the parent class name. Read the
+:doc:`Drivers <../general/drivers>` description for details.
+
+Additionally, multiple driver libraries can be loaded at the same time by
+passing an array of drivers to the load function.
+
+::
+
+ $this->load->driver(array('session', 'cache'));
+
+Setting options
+---------------
+
+The second (optional) parameter allows you to optionally pass
+configuration settings. You will typically pass these as an array::
+
+ $config = array (
+ 'sess_driver' => 'cookie',
+ 'sess_encrypt_cookie' => true,
+ 'encryption_key' => 'mysecretkey'
+ );
+
+ $this->load->driver('session', $config);
+
+Config options can usually also be set via a config file. Each library
+is explained in detail in its own page, so please read the information
+regarding each one you would like to use.
+
+Assigning a Driver to a different object name
+----------------------------------------------
+
+If the third (optional) parameter is blank, the library will be assigned
+to an object with the same name as the parent class. For example, if
the library is named Session, it will be assigned to a variable named
$this->session.
@@ -86,8 +151,8 @@ third parameter::
$this->my_session
-Please take note, when multiple libraries are supplied in an array for
-the first parameter, this parameter is discarded.
+.. note:: Driver libraries may also be loaded with the library() method,
+ but it is faster to use driver()
$this->load->view('file_name', $data, true/false)
==================================================
@@ -281,4 +346,4 @@ calling add_package_path().
// Again without the second parameter:
$this->load->add_package_path(APPPATH.'my_app', TRUE);
$this->load->view('my_app_index'); // Loads
- $this->load->view('welcome_message'); // Loads \ No newline at end of file
+ $this->load->view('welcome_message'); // Loads
diff --git a/user_guide_src/source/libraries/migration.rst b/user_guide_src/source/libraries/migration.rst
index 5192f1f29..cb7d96a6d 100644
--- a/user_guide_src/source/libraries/migration.rst
+++ b/user_guide_src/source/libraries/migration.rst
@@ -2,4 +2,136 @@
Migrations Class
################
-Coming soon. \ No newline at end of file
+Migrations are a convenient way for you to alter your database in a
+structured and organized manner. You could edit fragments of SQL by hand
+but you would then be responsible for telling other developers that they
+need to go and run them. You would also have to keep track of which changes
+need to be run against the production machines next time you deploy.
+
+The database table **migration** tracks which migrations have already been
+run so all you have to do is update your application files and
+call **$this->migrate->current()** to work out which migrations should be run.
+The current version is found in **config/migration.php**.
+
+******************
+Create a Migration
+******************
+
+.. note:: Each Migration is run in numerical order forward or backwards
+ depending on the method taken. Use a prefix of 3 numbers followed by an
+ underscore for the filename of your migration.
+
+This will be the first migration for a new site which has a blog. All
+migrations go in the folder **application/migrations/** and have names such
+as: **001_add_blog.php**.::
+
+ defined('BASEPATH') OR exit('No direct script access allowed');
+
+ class Migration_Add_blog extends CI_Migration {
+
+ public function up()
+ {
+ $this->dbforge->add_field(array(
+ 'blog_id' => array(
+ 'type' => 'INT',
+ 'constraint' => 5,
+ 'unsigned' => TRUE,
+ 'auto_increment' => TRUE
+ ),
+ 'blog_title' => array(
+ 'type' => 'VARCHAR',
+ 'constraint' => '100',
+ ),
+ 'blog_description' => array(
+ 'type' => 'TEXT',
+ 'null' => TRUE,
+ ),
+ ));
+
+ $this->dbforge->create_table('blog');
+ }
+
+ public function down()
+ {
+ $this->dbforge->drop_table('blog');
+ }
+
+Then in **application/config/migration.php** set **$config['migration_version'] = 1;**.
+
+*************
+Usage Example
+*************
+
+In this example some simple code is placed in **application/controllers/migrate.php**
+to update the schema.::
+
+ $this->load->library('migration');
+
+ if ( ! $this->migration->current())
+ {
+ show_error($this->migration->error_string());
+ }
+
+******************
+Function Reference
+******************
+
+There are five available methods for the Migration class:
+
+- $this->migration->current();
+- $this->migration->error_string();
+- $this->migration->find_migrations();
+- $this->migration->latest();
+- $this->migration->version();
+
+$this->migration->current()
+============================
+
+The current migration is whatever is set for **$config['migration_version']** in
+**application/config/migration.php**.
+
+$this->migration->error_string()
+=================================
+
+This returns a string of errors while performing a migration.
+
+$this->migration->find_migrations()
+====================================
+
+An array of migration filenames are returned that are found in the **migration_path**
+property.
+
+$this->migration->latest()
+===========================
+
+This works much the same way as current() but instead of looking for
+the **$config['migration_version']** the Migration class will use the very
+newest migration found in the filesystem.
+
+$this->migration->version()
+============================
+
+Version can be used to roll back changes or step forwards programmatically to
+specific versions. It works just like current but ignores **$config['migration_version']**.::
+
+ $this->load->library('migration');
+
+ $this->migration->version(5);
+
+*********************
+Migration Preferences
+*********************
+
+The following is a table of all the config options for migrations.
+
+========================== ====================== ============= =============================================
+Preference Default Options Description
+========================== ====================== ============= =============================================
+**migration_enabled** FALSE TRUE / FALSE Enable or disable migrations.
+**migration_path** APPPATH.'migrations/' None The path to your migrations folder.
+**migration_version** 0 None The current version your database should use.
+**migration_table** migrations None The table name for storing the shema
+ version number.
+**migration_auto_latest** FALSE TRUE / FALSE Enable or disable automatically
+ running migrations.
+========================== ====================== ============= =============================================
diff --git a/user_guide_src/source/libraries/sessions.rst b/user_guide_src/source/libraries/sessions.rst
index 5400524a9..dd9e8cbb4 100644
--- a/user_guide_src/source/libraries/sessions.rst
+++ b/user_guide_src/source/libraries/sessions.rst
@@ -1,29 +1,19 @@
-#############
-Session Class
-#############
+##############
+Session Driver
+##############
The Session class permits you maintain a user's "state" and track their
-activity while they browse your site. The Session class stores session
-information for each user as serialized (and optionally encrypted) data
-in a cookie. It can also store the session data in a database table for
-added security, as this permits the session ID in the user's cookie to
-be matched against the stored session ID. By default only the cookie is
-saved. If you choose to use the database option you'll need to create
-the session table as indicated below.
-
-.. note:: The Session class does **not** utilize native PHP sessions. It
- generates its own session data, offering more flexibility for
- developers.
-
-.. note:: Even if you are not using encrypted sessions, you must set
- an :doc:`encryption key <./encryption>` in your config file which is used
- to aid in preventing session data manipulation.
+activity while they browse your site. CodeIgniter offers two default
+session drivers: the classic `Cookie Driver`_, and the `Native Driver`_,
+which supports usage of the native PHP Session mechanism. In addition,
+you may create your own `Custom Drivers`_ to store session data however
+you wish, while still taking advantage of the features of the Session class.
Initializing a Session
======================
Sessions will typically run globally with each page load, so the session
-class must either be :doc:`initialized <../general/libraries>` in your
+class must either be :doc:`initialized <../general/drivers>` in your
:doc:`controller <../general/controllers>` constructors, or it can be
:doc:`auto-loaded <../general/autoloader>` by the system. For the most
part the session class will run unattended in the background, so simply
@@ -31,22 +21,25 @@ initializing the class will cause it to read, create, and update
sessions.
To initialize the Session class manually in your controller constructor,
-use the $this->load->library function::
+use the $this->load->driver function::
- $this->load->library('session');
+ $this->load->driver('session');
Once loaded, the Sessions library object will be available using:
$this->session
+.. note:: For backward compatibility, the Session class may stil be loaded
+ using the $this->load->library function, but converting your applications
+ to use $this->load->driver is strongly recommended.
+
How do Sessions work?
=====================
When a page is loaded, the session class will check to see if valid
-session data exists in the user's session cookie. If sessions data does
-**not** exist (or if it has expired) a new session will be created and
-saved in the cookie. If a session does exist, its information will be
-updated and the cookie will be updated. With each update, the
-session_id will be regenerated.
+session data exists in the user's session. If sessions data does **not**
+exist (or if it has expired) a new session will be created and saved.
+If a session does exist, its information will be updated. With each update,
+the session_id will be regenerated.
It's important for you to understand that once initialized, the Session
class runs automatically. There is nothing you need to do to cause the
@@ -79,19 +72,12 @@ prototype::
'last_activity' => timestamp
)
-If you have the encryption option enabled, the serialized array will be
-encrypted before being stored in the cookie, making the data highly
-secure and impervious to being read or altered by someone. More info
-regarding encryption can be :doc:`found here <encryption>`, although
-the Session class will take care of initializing and encrypting the data
-automatically.
-
-Note: Session cookies are only updated every five minutes by default to
-reduce processor load. If you repeatedly reload a page you'll notice
-that the "last activity" time only updates if five minutes or more has
-passed since the last time the cookie was written. This time is
-configurable by changing the $config['sess_time_to_update'] line in
-your system/config/config.php file.
+.. note:: Sessions are only updated every five minutes by default to
+ reduce processor load. If you repeatedly reload a page you'll notice
+ that the "last activity" time only updates if five minutes or more has
+ passed since the last time the cookie was written. This time is
+ configurable by changing the $config['sess_time_to_update'] line in
+ your system/config/config.php file.
Retrieving Session Data
=======================
@@ -106,7 +92,7 @@ fetch. For example, to fetch the session ID you will do this::
$session_id = $this->session->userdata('session_id');
-.. note:: The function returns FALSE (boolean) if the item you are
+.. note:: The function returns NULL if the item you are
trying to access does not exist.
Adding Custom Session Data
@@ -117,7 +103,7 @@ to it and it will be stored in the user's cookie. Why would you want to
do this? Here's one example:
Let's say a particular user logs into your site. Once authenticated, you
-could add their username and email address to the session cookie, making
+could add their username and email address to the session, making
that data globally available to you without having to run a database
query when you need it.
@@ -144,11 +130,11 @@ supports this syntax.
$this->session->set_userdata('some_name', 'some_value');
+If you want to verify that a userdata value exists, call has_userdata().
-.. note:: Cookies can only hold 4KB of data, so be careful not to exceed
- the capacity. The encryption process in particular produces a longer
- data string than the original so keep careful track of how much data you
- are storing.
+::
+
+ $this->session->has_userdata('some_name');
Retrieving All Session Data
===========================
@@ -195,8 +181,8 @@ available for the next server request, and are then automatically
cleared. These can be very useful, and are typically used for
informational or status messages (for example: "record 2 deleted").
-Note: Flash variables are prefaced with "flash\_" so avoid this prefix
-in your own session names.
+.. note:: Flash variables are prefaced with "flash\_" so avoid this prefix
+ in your own session names.
To add flashdata::
@@ -222,9 +208,162 @@ additional request, you can do so using the keep_flashdata() function.
$this->session->keep_flashdata('item');
+Tempdata
+========
+
+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.
+
+To add tempdata::
+
+ $expire = 300; // Expire in 5 minutes
+
+ $this->session->set_tempdata('item', 'value', $expire);
+
+You can also pass an array to set_tempdata()::
+
+ $tempdata = array('newuser' => TRUE, 'message' => 'Thanks for joining!');
+
+ $this->session->set_tempdata($tempdata, '', $expire);
+
+.. note:: If the expiration is omitted or set to 0, the default expiration of
+ 5 minutes will be used.
+
+To read a tempdata variable::
+
+ $this->session->tempdata('item');
+
+If you need to remove a tempdata value before it expires,
+use unset_tempdata()::
+
+ $this->session->unset_tempdata('item');
+
+Destroying a Session
+====================
+
+To clear the current session::
+
+ $this->session->sess_destroy();
+
+.. note:: This function should be the last one called, and even flash
+ variables will no longer be available. If you only want some items
+ destroyed and not all, use unset_userdata().
+
+Session Preferences
+===================
+
+You'll find the following Session related preferences in your
+application/config/config.php file:
+
+=========================== =============== =========================== ==========================================================================
+Preference Default Options Description
+=========================== =============== =========================== ==========================================================================
+**sess_driver** cookie cookie/native/*custom* The initial session driver to load.
+**sess_valid_drivers** cookie, native None Additional valid drivers which may be loaded.
+**sess_cookie_name** ci_session None The name you want the session cookie saved as (data for Cookie driver or
+ session ID for Native driver).
+**sess_expiration** 7200 None The number of seconds you would like the session to last. The default
+ value is 2 hours (7200 seconds). If you would like a non-expiring
+ session set the value to zero: 0
+**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser
+ window is closed.
+**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data (Cookie driver only).
+**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the
+ table before enabling this option (Cookie driver only).
+**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table (Cookie driver only).
+**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself
+ and create a new session id.
+**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data.
+ Note that some ISPs dynamically changes the IP, so if you want a
+ non-expiring session you will likely set this to FALSE.
+**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data.
+=========================== =============== =========================== ==========================================================================
+
+In addition to the values above, the cookie and native drivers apply the
+following configuration values shared by the :doc:`Input <input>` and
+:doc:`Security <security>` classes:
+
+=========================== =============== ==========================================================================
+Preference Default Description
+=========================== =============== ==========================================================================
+**cookie_prefix** '' Set a cookie name prefix in order to avoid name collisions
+**cookie_domain** '' The domain for which the session is applicable
+**cookie_path** / The path to which the session is applicable
+=========================== =============== ==========================================================================
+
+Session Drivers
+===============
+
+By default, the `Cookie Driver`_ is loaded when a session is initialized.
+However, any valid driver may be selected with the $config['sess_driver']
+line in your config.php file.
+
+The session driver library comes with the cookie and native drivers
+installed, and `Custom Drivers`_ may also be installed by the user.
+
+Typically, only one driver will be used at a time, but CodeIgniter does
+support loading multiple drivers. If a specific valid driver is called, it
+will be automatically loaded. Or, an additional driver may be explicitly
+loaded by calling load_driver()::
+
+ $this->session->load_driver('native');
+
+The Session library keeps track of the most recently selected driver to call
+for driver methods. Normally, session class methods are called directly on
+the parent class, as illustrated above. However, any methods called through
+a specific driver will select that driver before invoking the parent method.
+
+So, alternation between multiple drivers can be achieved by specifying which
+driver to use for each call::
+
+ $this->session->native->set_userdata('foo', 'bar');
+
+ $this->session->cookie->userdata('foo');
+
+ $this->session->native->unset_userdata('foo');
+
+Notice in the previous example that the *native* userdata value 'foo'
+would be set to 'bar', which would NOT be returned by the call for
+the *cookie* userdata 'foo', nor would the *cookie* value be unset by
+the call to unset the *native* 'foo' value. The drivers maintain independent
+sets of values, regardless of key names.
+
+A specific driver may also be explicitly selected for use by pursuant
+methods with the select_driver() call::
+
+ $this->session->select_driver('native');
+
+ $this->session->userdata('item'); // Uses the native driver
+
+Cookie Driver
+-------------
+
+The Cookie driver stores session information for each user as serialized
+(and optionally encrypted) data in a cookie. It can also store the session
+data in a database table for added security, as this permits the session ID
+in the user's cookie to be matched against the stored session ID. By default
+only the cookie is saved. If you choose to use the database option you'll
+need to create the session table as indicated below.
+
+If you have the encryption option enabled, the serialized array will be
+encrypted before being stored in the cookie, making the data highly
+secure and impervious to being read or altered by someone. More info
+regarding encryption can be :doc:`found here <encryption>`, although
+the Session class will take care of initializing and encrypting the data
+automatically.
+
+.. note:: Even if you are not using encrypted sessions, you must set
+ an :doc:`encryption key <./encryption>` in your config file which is used
+ to aid in preventing session data manipulation.
+
+.. note:: Cookies can only hold 4KB of data, so be careful not to exceed
+ the capacity. The encryption process in particular produces a longer
+ data string than the original so keep careful track of how much data you
+ are storing.
Saving Session Data to a Database
-=================================
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
While the session data array stored in the user's cookie contains a
Session ID, unless you store session data in a database there is no way
@@ -267,44 +406,83 @@ session class::
$config['sess_table_name'] = 'ci_sessions';
-.. note:: The Session class has built-in garbage collection which clears
+.. note:: The Cookie driver has built-in garbage collection which clears
out expired sessions so you do not need to write your own routine to do
it.
-Destroying a Session
-====================
+Native Driver
+-------------
-To clear the current session::
+The Native driver relies on native PHP sessions to store data in the
+$_SESSION superglobal array. All stored values continue to be available
+through $_SESSION, but flash- and temp- data items carry special prefixes.
- $this->session->sess_destroy();
+Custom Drivers
+--------------
-.. note:: This function should be the last one called, and even flash
- variables will no longer be available. If you only want some items
- destroyed and not all, use unset_userdata().
+You may also :doc:`create your own <../general/creating_drivers>` custom
+session drivers. A session driver basically manages an array of name/value
+pairs with some sort of storage mechanism.
-Session Preferences
-===================
+To make a new driver, extend CI_Session_driver. Overload the initialize()
+method and read or create session data. Then implement a save handler to
+write changed data to storage (sess_save), a destroy handler to remove
+deleted data (sess_destroy), a regenerate handler to make a new session ID
+(sess_regenerate), and an access handler to expose the data (get_userdata).
+Your initial class might look like::
-You'll find the following Session related preferences in your
-application/config/config.php file:
+ class CI_Session_custom extends CI_Session_driver {
+ protected function initialize()
+ {
+ // Read existing session data or create a new one
+ }
+
+ public function sess_save()
+ {
+ // Save current data to storage
+ }
+
+ public function sess_destroy()
+ {
+ // Destroy the current session and clean up storage
+ }
+
+ public function sess_regenerate()
+ {
+ // Create new session ID
+ }
+
+ public function &get_userdata()
+ {
+ // Return a reference to your userdata array
+ }
+ }
+
+Notice that get_userdata() returns a reference so the parent library is
+accessing the same array the driver object is using. This saves memory
+and avoids synchronization issues during usage.
+
+Put your driver in the libraries/Session/drivers folder anywhere in your
+package paths. This includes the application directory, the system directory,
+or any path you add with $CI->load->add_package_path(). Your driver must be
+named CI_Session_<name>, and your filename must be Session_<name>.php,
+preferably also capitalized, such as::
+
+ CI_Session_foo in libraries/Session/drivers/Session_foo.php
+
+Then specify the driver by setting 'sess_driver' in your config.php file or as a
+parameter when loading the CI_Session object::
+
+ $config['sess_driver'] = 'foo';
+
+OR::
+
+ $CI->load->driver('session', array('sess_driver' => 'foo'));
+
+The driver specified by 'sess_driver' is automatically included as a valid
+driver. However, if you want to make a custom driver available as an option
+without making it the initially loaded driver, set 'sess_valid_drivers' in
+your config.php file to an array including your driver name::
+
+ $config['sess_valid_drivers'] = array('sess_driver');
-=========================== =============== =========================== ==========================================================================
-Preference Default Options Description
-=========================== =============== =========================== ==========================================================================
-**sess_cookie_name** ci_session None The name you want the session cookie saved as.
-**sess_expiration** 7200 None The number of seconds you would like the session to last. The default
- value is 2 hours (7200 seconds). If you would like a non-expiring
- session set the value to zero: 0
-**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser
- window is closed.
-**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data.
-**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the
- table before enabling this option.
-**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table.
-**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself
- and create a new session id.
-**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data.
- Note that some ISPs dynamically changes the IP, so if you want a
- non-expiring session you will likely set this to FALSE.
-**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data.
-=========================== =============== =========================== ========================================================================== \ No newline at end of file