summaryrefslogtreecommitdiffstats
path: root/user_guide_src/source/libraries
diff options
context:
space:
mode:
Diffstat (limited to 'user_guide_src/source/libraries')
-rw-r--r--user_guide_src/source/libraries/cart.rst3
-rw-r--r--user_guide_src/source/libraries/encryption.rst1
-rw-r--r--user_guide_src/source/libraries/form_validation.rst10
-rw-r--r--user_guide_src/source/libraries/input.rst56
-rw-r--r--user_guide_src/source/libraries/javascript.rst8
-rw-r--r--user_guide_src/source/libraries/language.rst101
-rw-r--r--user_guide_src/source/libraries/loader.rst3
-rw-r--r--user_guide_src/source/libraries/output.rst1
-rw-r--r--user_guide_src/source/libraries/pagination.rst84
-rw-r--r--user_guide_src/source/libraries/parser.rst242
-rw-r--r--user_guide_src/source/libraries/security.rst6
-rw-r--r--user_guide_src/source/libraries/sessions.rst1157
-rw-r--r--user_guide_src/source/libraries/trackback.rst2
-rw-r--r--user_guide_src/source/libraries/unit_testing.rst4
-rw-r--r--user_guide_src/source/libraries/zip.rst70
15 files changed, 1158 insertions, 590 deletions
diff --git a/user_guide_src/source/libraries/cart.rst b/user_guide_src/source/libraries/cart.rst
index bedea4dbf..3c0a79178 100644
--- a/user_guide_src/source/libraries/cart.rst
+++ b/user_guide_src/source/libraries/cart.rst
@@ -7,6 +7,9 @@ while a user is browsing your site. These items can be retrieved and
displayed in a standard "shopping cart" format, allowing the user to
update the quantity or remove items from the cart.
+.. important:: The Cart library is DEPRECATED and should not be used.
+ It is currently only kept for backwards compatibility.
+
Please note that the Cart Class ONLY provides the core "cart"
functionality. It does not provide shipping, credit card authorization,
or other processing components.
diff --git a/user_guide_src/source/libraries/encryption.rst b/user_guide_src/source/libraries/encryption.rst
index f29ebf4ed..2d0ee23a3 100644
--- a/user_guide_src/source/libraries/encryption.rst
+++ b/user_guide_src/source/libraries/encryption.rst
@@ -533,6 +533,7 @@ Class Reference
:param int $length: Optional output length
:param string $info: Optional context/application-specific info
:returns: A pseudo-random key or FALSE on failure
+ :rtype: string
Derives a key from another, presumably weaker key.
diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst
index 69b6c688a..4ba3a33b7 100644
--- a/user_guide_src/source/libraries/form_validation.rst
+++ b/user_guide_src/source/libraries/form_validation.rst
@@ -326,14 +326,13 @@ In addition to the validation method like the ones we used above, you
can also prep your data in various ways. For example, you can set up
rules like this::
- $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
+ $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
-In the above example, we are "trimming" the fields, converting the
-password to MD5, and running the username through the `xss_clean()`
-method, which removes malicious data.
+In the above example, we are "trimming" the fields, checking for length
+where necessary and converting the password to MD5.
**Any native PHP function that accepts one parameter can be used as a
rule, like htmlspecialchars, trim, md5, etc.**
@@ -519,7 +518,7 @@ the second element of an array, with the first one being the rule name::
'username', 'Username',
array(
'required',
- array('username_callable', array($this->users_model', 'valid_username'))
+ array('username_callable', array($this->users_model, 'valid_username'))
)
);
@@ -1003,7 +1002,6 @@ to use:
==================== ========= =======================================================================================================
Name Parameter Description
==================== ========= =======================================================================================================
-**xss_clean** No Runs the data through the XSS filtering method, described in the :doc:`Security Class <security>` page.
**prep_for_form** No Converts special characters so that HTML data can be shown in a form field without breaking it.
**prep_url** No Adds "\http://" to URLs if missing.
**strip_image_tags** No Strips the HTML from image tags leaving the raw URL.
diff --git a/user_guide_src/source/libraries/input.rst b/user_guide_src/source/libraries/input.rst
index f9dbf1686..4464e0fdc 100644
--- a/user_guide_src/source/libraries/input.rst
+++ b/user_guide_src/source/libraries/input.rst
@@ -17,6 +17,10 @@ The Input Class serves two purposes:
<div class="custom-index container"></div>
+***************
+Input Filtering
+***************
+
Security Filtering
==================
@@ -49,6 +53,10 @@ this::
Please refer to the :doc:`Security class <security>` documentation for
information on using XSS Filtering in your application.
+*******************
+Accessing form data
+*******************
+
Using POST, GET, COOKIE, or SERVER Data
=======================================
@@ -108,7 +116,7 @@ Class Reference
.. method:: post([$index = NULL[, $xss_clean = NULL]])
- :param string $index: POST parameter name
+ :param mixed $index: POST parameter name
:param bool $xss_clean: Whether to apply XSS filtering
:returns: $_POST if no parameters supplied, otherwise the POST value if found or NULL if not
:rtype: mixed
@@ -137,9 +145,21 @@ Class Reference
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(NULL, FALSE); // returns all POST items without XSS filter
+ To return an array of multiple POST parameters, pass all the required keys
+ as an array.
+ ::
+
+ $this->input->post(array('field1', 'field2'));
+
+ Same rule applied here, to retrive the parameters with XSS filtering enabled, set the
+ second parameter to boolean TRUE.
+ ::
+
+ $this->input->post(array('field1', 'field2'), TRUE);
+
.. method:: get([$index = NULL[, $xss_clean = NULL]])
- :param string $index: GET parameter name
+ :param mixed $index: GET parameter name
:param bool $xss_clean: Whether to apply XSS filtering
:returns: $_GET if no parameters supplied, otherwise the GET value if found or NULL if not
:rtype: mixed
@@ -158,6 +178,18 @@ Class Reference
$this->input->get(NULL, TRUE); // returns all GET items with XSS filter
$this->input->get(NULL, FALSE); // returns all GET items without XSS filtering
+ To return an array of multiple GET parameters, pass all the required keys
+ as an array.
+ ::
+
+ $this->input->get(array('field1', 'field2'));
+
+ Same rule applied here, to retrive the parameters with XSS filtering enabled, set the
+ second parameter to boolean TRUE.
+ ::
+
+ $this->input->get(array('field1', 'field2'), TRUE);
+
.. method:: post_get($index[, $xss_clean = NULL])
:param string $index: POST/GET parameter name
@@ -188,7 +220,7 @@ Class Reference
.. method:: cookie([$index = NULL[, $xss_clean = NULL]])
- :param string $index: COOKIE parameter name
+ :param mixed $index: COOKIE name
:param bool $xss_clean: Whether to apply XSS filtering
:returns: $_COOKIE if no parameters supplied, otherwise the COOKIE value if found or NULL if not
:rtype: mixed
@@ -199,9 +231,15 @@ Class Reference
$this->input->cookie('some_cookie');
$this->input->cookie('some_cookie, TRUE); // with XSS filter
+ To return an array of multiple cookie values, pass all the required keys
+ as an array.
+ ::
+
+ $this->input->cookie(array('some_cookie', 'some_cookie2'));
+
.. method:: server($index[, $xss_clean = NULL])
- :param string $index: Value name
+ :param mixed $index: Value name
:param bool $xss_clean: Whether to apply XSS filtering
:returns: $_SERVER item value if found, NULL if not
:rtype: mixed
@@ -211,9 +249,15 @@ Class Reference
$this->input->server('some_data');
+ To return an array of multiple ``$_SERVER`` values, pass all the required keys
+ as an array.
+ ::
+
+ $this->input->server(array('SERVER_PROTOCOL', 'REQUEST_URI'));
+
.. method:: input_stream([$index = NULL[, $xss_clean = NULL]])
- :param string $index: Key name
+ :param mixed $index: Key name
:param bool $xss_clean: Whether to apply XSS filtering
:returns: Input stream array if no parameters supplied, otherwise the specified value if found or NULL if not
:rtype: mixed
@@ -407,4 +451,4 @@ Class Reference
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
- echo $this->input->method(); // Outputs: post \ No newline at end of file
+ echo $this->input->method(); // Outputs: post
diff --git a/user_guide_src/source/libraries/javascript.rst b/user_guide_src/source/libraries/javascript.rst
index 9d0237e57..7f83b2f70 100644
--- a/user_guide_src/source/libraries/javascript.rst
+++ b/user_guide_src/source/libraries/javascript.rst
@@ -2,16 +2,16 @@
Javascript Class
################
-.. note:: This library is DEPRECATED and should not be used. It has always
- been with an 'experimental' status and is now no longer supported.
- Currently only kept for backwards compatibility.
-
CodeIgniter provides a library to help you with certain common functions
that you may want to use with Javascript. Please note that CodeIgniter
does not require the jQuery library to run, and that any scripting
library will work equally well. The jQuery library is simply presented
as a convenience if you choose to use it.
+.. important:: This library is DEPRECATED and should not be used. It has always
+ been with an 'experimental' status and is now no longer supported.
+ Currently only kept for backwards compatibility.
+
.. contents::
:local:
diff --git a/user_guide_src/source/libraries/language.rst b/user_guide_src/source/libraries/language.rst
index 3014d8f09..e833d9757 100644
--- a/user_guide_src/source/libraries/language.rst
+++ b/user_guide_src/source/libraries/language.rst
@@ -5,16 +5,25 @@ Language Class
The Language Class provides functions to retrieve language files and
lines of text for purposes of internationalization.
-In your CodeIgniter system folder you'll find one called language
-containing sets of language files. You can create your own language
-files as needed in order to display error and other messages in other
-languages.
-
-Language files are typically stored in your **system/language/** directory.
-Alternately you can create a directory called language inside your
-application folder and store them there. CodeIgniter will always load the
-one in **system/language/** first and will then look for an override in
-your **application/language/** directory.
+In your CodeIgniter **system** folder, you will find a **language** sub-directory
+containing a set of language files for the **english** idiom.
+The files in this directory (**system/language/english/**) define the regular messages,
+error messages, and other generally output terms or expressions, for the different parts
+of the CodeIgniter framework.
+
+You can create or incorporate your own language files, as needed, in order to provide
+application-specific error and other messages, or to provide translations of the core
+messages into other languages. These translations or additional messages would go inside
+your **application/language/** directory, with separate sub-directories for each idiom
+(for instance, 'french' or 'german').
+
+The CodeIgniter framework comes with a set of language files for the "english" idiom.
+Additional approved translations for different idioms may be found in the
+`CodeIgniter 3 Translations repositories <https://github.com/codeigniter3-translations>`_.
+Each repository deals with a single idiom.
+
+When CodeIgniter loads language files, it will load the one in **system/language/**
+first and will then look for an override in your **application/language/** directory.
.. note:: Each language should be stored in its own folder. For example,
the English files are located at: system/language/english
@@ -26,6 +35,71 @@ your **application/language/** directory.
<div class="custom-index container"></div>
+***************************
+Handling Multiple Languages
+***************************
+
+If you want to support multiple languages in your application, you would provide folders inside
+your **application/language/** directory for each of them, and you would specify the default
+language in your **application/config/config.php**.
+
+The **application/language/english/** directory would contain any additional language files
+needed by your application, for instance for error messages.
+
+Each of the other idiom-specific directories would contain the core language files that you
+obtained from the translations repositories, or that you translated yourself, as well as
+any additional ones needed by your application.
+
+You would store the language you are currently using, for instance in a session variable.
+
+Sample Language Files
+=====================
+
+::
+
+ system/
+ language/
+ english/
+ ...
+ email_lang.php
+ form_validation_lang.php
+ ...
+
+ application/
+ language/
+ english/
+ error_messages_lang.php
+ french/
+ ...
+ email_lang.php
+ error_messages_lang.php
+ form_validation_lang.php
+ ...
+
+Example of switching languages
+==============================
+
+::
+
+ $idiom = $this->session->get_userdata('language');
+ $this->lang->load('error_messages', $idiom);
+ $oops = $this->lang->line('message_key');
+
+********************
+Internationalization
+********************
+
+The Language class in CodeIgniter is meant to provide an easy and lightweight
+way to support multiplelanguages in your application. It is not meant to be a
+full implementation of what is commonly called `internationalization and localization
+<http://en.wikipedia.org/wiki/Internationalization_and_localization>`_.
+
+We use the term "idiom" to refer to a language using its common name,
+rather than using any of the international standards, such as "en", "en-US",
+or "en-CA-x-ca" for English and some of its variants.
+
+.. note:: There is nothing to prevent you from using those abbreviations in your application!
+
************************
Using the Language Class
************************
@@ -66,6 +140,11 @@ file extension), and language is the language set containing it (ie,
english). If the second parameter is missing, the default language set
in your **application/config/config.php** file will be used.
+You can also load multiple language files at the same time by passing an array of language files as first parameter.
+::
+
+ $this->lang->load(array('filename1', 'filename2'));
+
.. note:: The *language* parameter can only consist of letters.
Fetching a Line of Text
@@ -110,7 +189,7 @@ Class Reference
.. method:: load($langfile[, $idiom = ''[, $return = FALSE[, $add_suffix = TRUE[, $alt_path = '']]]])
- :param string $langfile: Language file to load
+ :param mixed $langfile: Language file to load or array with multiple files
:param string $idiom: Language name (i.e. 'english')
:param bool $return: Whether to return the loaded array of translations
:param bool $add_suffix: Whether to add the '_lang' suffix to the language file name
diff --git a/user_guide_src/source/libraries/loader.rst b/user_guide_src/source/libraries/loader.rst
index 107b3ece3..48ac6e174 100644
--- a/user_guide_src/source/libraries/loader.rst
+++ b/user_guide_src/source/libraries/loader.rst
@@ -18,8 +18,9 @@ can be libraries (classes) :doc:`View files <../general/views>`,
<div class="custom-index container"></div>
+**********************
Application "Packages"
-======================
+**********************
An application package allows for the easy distribution of complete sets
of resources in a single directory, complete with its own libraries,
diff --git a/user_guide_src/source/libraries/output.rst b/user_guide_src/source/libraries/output.rst
index 218ec5896..e808561bd 100644
--- a/user_guide_src/source/libraries/output.rst
+++ b/user_guide_src/source/libraries/output.rst
@@ -220,6 +220,7 @@ Class Reference
call it manually unless you are aborting script execution using ``exit()`` or ``die()`` in your code.
Example::
+
$response = array('status' => 'OK');
$this->output
diff --git a/user_guide_src/source/libraries/pagination.rst b/user_guide_src/source/libraries/pagination.rst
index 8a62376f1..d51d0dd27 100644
--- a/user_guide_src/source/libraries/pagination.rst
+++ b/user_guide_src/source/libraries/pagination.rst
@@ -73,29 +73,25 @@ Customizing the Pagination
The following is a list of all the preferences you can pass to the
initialization function to tailor the display.
-$config['uri_segment'] = 3;
-===========================
+**$config['uri_segment'] = 3;**
The pagination function automatically determines which segment of your
URI contains the page number. If you need something different you can
specify it.
-$config['num_links'] = 2;
-=========================
+**$config['num_links'] = 2;**
The number of "digit" links you would like before and after the selected
page number. For example, the number 2 will place two digits on either
side, as in the example links at the very top of this page.
-$config['use_page_numbers'] = TRUE;
-===================================
+**$config['use_page_numbers'] = TRUE;**
By default, the URI segment will use the starting index for the items
you are paginating. If you prefer to show the the actual page number,
set this to TRUE.
-$config['page_query_string'] = TRUE;
-====================================
+**$config['page_query_string'] = TRUE;**
By default, the pagination library assume you are using :doc:`URI
Segments <../general/urls>`, and constructs your links something
@@ -113,8 +109,7 @@ the pagination link will become::
Note that "per_page" is the default query string passed, however can be
configured using ``$config['query_string_segment'] = 'your_string'``
-$config['reuse_query_string'] = FALSE;
-======================================
+**$config['reuse_query_string'] = FALSE;**
By default your Query String arguments (nothing to do with other
query string options) will be ignored. Setting this config to
@@ -126,18 +121,22 @@ URL after the URI segment and before the suffix.::
This helps you mix together normal :doc:`URI Segments <../general/urls>`
as well as query string arguments, which until 3.0 was not possible.
-$config['prefix'] = '';
-=======================
+**$config['prefix'] = '';**
A custom prefix added to the path. The prefix value will be right before
the offset segment.
-$config['suffix'] = '';
-=======================
+**$config['suffix'] = '';**
A custom suffix added to the path. The sufix value will be right after
the offset segment.
+**$config['use_global_url_suffix'] = FALSE;**
+
+When set to TRUE, it will **override** the ``$config['suffix']`` value and
+instead set it to the one that you have in ``$config['url_suffix']`` in
+your **application/config/config.php** file.
+
***********************
Adding Enclosing Markup
***********************
@@ -145,13 +144,11 @@ Adding Enclosing Markup
If you would like to surround the entire pagination with some markup you
can do it with these two preferences:
-$config['full_tag_open'] = '<p>';
-=================================
+**$config['full_tag_open'] = '<p>';**
The opening tag placed on the left side of the entire result.
-$config['full_tag_close'] = '</p>';
-===================================
+**$config['full_tag_close'] = '</p>';**
The closing tag placed on the right side of the entire result.
@@ -159,26 +156,22 @@ The closing tag placed on the right side of the entire result.
Customizing the First Link
**************************
-$config['first_link'] = 'First';
-================================
+**$config['first_link'] = 'First';**
The text you would like shown in the "first" link on the left. If you do
not want this link rendered, you can set its value to FALSE.
.. note:: This value can also be translated via a language file.
-$config['first_tag_open'] = '<div>';
-====================================
+**$config['first_tag_open'] = '<div>';**
The opening tag for the "first" link.
-$config['first_tag_close'] = '</div>';
-======================================
+**$config['first_tag_close'] = '</div>';**
The closing tag for the "first" link.
-$config['first_url'] = '';
-==========================
+**$config['first_url'] = '';**
An alternative URL to use for the "first page" link.
@@ -186,21 +179,18 @@ An alternative URL to use for the "first page" link.
Customizing the Last Link
*************************
-$config['last_link'] = 'Last';
-==============================
+**$config['last_link'] = 'Last';**
The text you would like shown in the "last" link on the right. If you do
not want this link rendered, you can set its value to FALSE.
.. note:: This value can also be translated via a language file.
-$config['last_tag_open'] = '<div>';
-===================================
+**$config['last_tag_open'] = '<div>';**
The opening tag for the "last" link.
-$config['last_tag_close'] = '</div>';
-=====================================
+**$config['last_tag_close'] = '</div>';**
The closing tag for the "last" link.
@@ -208,21 +198,18 @@ The closing tag for the "last" link.
Customizing the "Next" Link
***************************
-$config['next_link'] = '&gt;';
-==============================
+**$config['next_link'] = '&gt;';**
The text you would like shown in the "next" page link. If you do not
want this link rendered, you can set its value to FALSE.
.. note:: This value can also be translated via a language file.
-$config['next_tag_open'] = '<div>';
-===================================
+**$config['next_tag_open'] = '<div>';**
The opening tag for the "next" link.
-$config['next_tag_close'] = '</div>';
-=====================================
+**$config['next_tag_close'] = '</div>';**
The closing tag for the "next" link.
@@ -230,21 +217,18 @@ The closing tag for the "next" link.
Customizing the "Previous" Link
*******************************
-$config['prev_link'] = '&lt;';
-==============================
+**$config['prev_link'] = '&lt;';**
The text you would like shown in the "previous" page link. If you do not
want this link rendered, you can set its value to FALSE.
.. note:: This value can also be translated via a language file.
-$config['prev_tag_open'] = '<div>';
-===================================
+**$config['prev_tag_open'] = '<div>';**
The opening tag for the "previous" link.
-$config['prev_tag_close'] = '</div>';
-=====================================
+**$config['prev_tag_close'] = '</div>';**
The closing tag for the "previous" link.
@@ -252,13 +236,11 @@ The closing tag for the "previous" link.
Customizing the "Current Page" Link
***********************************
-$config['cur_tag_open'] = '<b>';
-================================
+**$config['cur_tag_open'] = '<b>';**
The opening tag for the "current" link.
-$config['cur_tag_close'] = '</b>';
-==================================
+**$config['cur_tag_close'] = '</b>';**
The closing tag for the "current" link.
@@ -266,13 +248,11 @@ The closing tag for the "current" link.
Customizing the "Digit" Link
****************************
-$config['num_tag_open'] = '<div>';
-==================================
+**$config['num_tag_open'] = '<div>';**
The opening tag for the "digit" link.
-$config['num_tag_close'] = '</div>';
-====================================
+**$config['num_tag_close'] = '</div>';**
The closing tag for the "digit" link.
diff --git a/user_guide_src/source/libraries/parser.rst b/user_guide_src/source/libraries/parser.rst
index 5af504a03..d66684d9b 100644
--- a/user_guide_src/source/libraries/parser.rst
+++ b/user_guide_src/source/libraries/parser.rst
@@ -2,24 +2,26 @@
Template Parser Class
#####################
-The Template Parser Class enables you to parse pseudo-variables
-contained within your view files. It can parse simple variables or
-variable tag pairs. If you've never used a template engine,
-pseudo-variables look like this::
+The Template Parser Class can perform simple text substitution for
+pseudo-variables contained within your view files.
+It can parse simple variables or variable tag pairs.
+
+If you've never used a template engine,
+pseudo-variable names are enclosed in braces, like this::
<html>
- <head>
- <title>{blog_title}</title>
- </head>
- <body>
-
- <h3>{blog_heading}</h3>
-
- {blog_entries}
- <h5>{title}</h5>
- <p>{body}</p>
- {/blog_entries}
- </body>
+ <head>
+ <title>{blog_title}</title>
+ </head>
+ <body>
+ <h3>{blog_heading}</h3>
+
+ {blog_entries}
+ <h5>{title}</h5>
+ <p>{body}</p>
+ {/blog_entries}
+
+ </body>
</html>
These variables are not actual PHP variables, but rather plain text
@@ -28,8 +30,9 @@ representations that allow you to eliminate PHP from your templates
.. note:: CodeIgniter does **not** require you to use this class since
using pure PHP in your view pages lets them run a little faster.
- However, some developers prefer to use a template engine if they work
- with designers who they feel would find some confusion working with PHP.
+ However, some developers prefer to use a template engine if
+ they work with designers who they feel would find some
+ confusion working with PHP.
.. important:: The Template Parser Class is **not** a full-blown
template parsing solution. We've kept it very lean on purpose in order
@@ -42,11 +45,15 @@ representations that allow you to eliminate PHP from your templates
<div class="custom-index container"></div>
+*******************************
+Using the Template Parser Class
+*******************************
+
Initializing the Class
======================
Like most other classes in CodeIgniter, the Parser class is initialized
-in your controller using the $this->load->library function::
+in your controller using the ``$this->load->library()`` method::
$this->load->library('parser');
@@ -56,12 +63,13 @@ $this->parser
Parsing templates
=================
-You can use the ``parse()`` method to parse (or render) simple templates, like this::
+You can use the ``parse()`` method to parse (or render) simple templates,
+like this::
$data = array(
- 'blog_title' => 'My Blog Title',
- 'blog_heading' => 'My Blog Heading'
- );
+ 'blog_title' => 'My Blog Title',
+ 'blog_heading' => 'My Blog Heading'
+ );
$this->parser->parse('blog_template', $data);
@@ -74,7 +82,7 @@ template would contain two variables: {blog_title} and {blog_heading}
There is no need to "echo" or do something with the data returned by
$this->parser->parse(). It is automatically passed to the output class
to be sent to the browser. However, if you do want the data returned
-instead of sent to the output class you can pass TRUE (boolean) to the
+instead of sent to the output class you can pass TRUE (boolean) as the
third parameter::
$string = $this->parser->parse('blog_template', $data, TRUE);
@@ -88,24 +96,24 @@ iteration containing new values? Consider the template example we showed
at the top of the page::
<html>
- <head>
- <title>{blog_title}</title>
- </head>
- <body>
-
- <h3>{blog_heading}</h3>
-
- {blog_entries}
- <h5>{title}</h5>
- <p>{body}</p>
- {/blog_entries}
- </body>
+ <head>
+ <title>{blog_title}</title>
+ </head>
+ <body>
+ <h3>{blog_heading}</h3>
+
+ {blog_entries}
+ <h5>{title}</h5>
+ <p>{body}</p>
+ {/blog_entries}
+
+ </body>
</html>
In the above code you'll notice a pair of variables: {blog_entries}
data... {/blog_entries}. In a case like this, the entire chunk of data
between these pairs would be repeated multiple times, corresponding to
-the number of rows in a result.
+the number of rows in the "blog_entries" element of the parameters array.
Parsing variable pairs is done using the identical code shown above to
parse single variables, except, you will add a multi-dimensional array
@@ -114,35 +122,156 @@ corresponding to your variable pair data. Consider this example::
$this->load->library('parser');
$data = array(
- 'blog_title' => 'My Blog Title',
- 'blog_heading' => 'My Blog Heading',
- 'blog_entries' => array(
- array('title' => 'Title 1', 'body' => 'Body 1'),
- array('title' => 'Title 2', 'body' => 'Body 2'),
- array('title' => 'Title 3', 'body' => 'Body 3'),
- array('title' => 'Title 4', 'body' => 'Body 4'),
- array('title' => 'Title 5', 'body' => 'Body 5')
- )
- );
+ 'blog_title' => 'My Blog Title',
+ 'blog_heading' => 'My Blog Heading',
+ 'blog_entries' => array(
+ array('title' => 'Title 1', 'body' => 'Body 1'),
+ array('title' => 'Title 2', 'body' => 'Body 2'),
+ array('title' => 'Title 3', 'body' => 'Body 3'),
+ array('title' => 'Title 4', 'body' => 'Body 4'),
+ array('title' => 'Title 5', 'body' => 'Body 5')
+ )
+ );
$this->parser->parse('blog_template', $data);
If your "pair" data is coming from a database result, which is already a
-multi-dimensional array, you can simply use the database result_array()
-function::
+multi-dimensional array, you can simply use the database ``result_array()``
+method::
$query = $this->db->query("SELECT * FROM blog");
$this->load->library('parser');
$data = array(
- 'blog_title' => 'My Blog Title',
- 'blog_heading' => 'My Blog Heading',
- 'blog_entries' => $query->result_array()
- );
+ 'blog_title' => 'My Blog Title',
+ 'blog_heading' => 'My Blog Heading',
+ 'blog_entries' => $query->result_array()
+ );
$this->parser->parse('blog_template', $data);
+Usage Notes
+===========
+
+If you include substitution parameters that are not referenced in your
+template, they are ignored::
+
+ $template = 'Hello, {firstname} {lastname}';
+ $data = array(
+ 'title' => 'Mr',
+ 'firstname' => 'John',
+ 'lastname' => 'Doe'
+ );
+ $this->parser->parse_string($template, $data);
+
+ // Result: Hello, John Doe
+
+If you do not include a substitution parameter that is referenced in your
+template, the original pseudo-variable is shown in the result::
+
+ $template = 'Hello, {firstname} {initials} {lastname}';
+ $data = array(
+ 'title' => 'Mr',
+ 'firstname' => 'John',
+ 'lastname' => 'Doe'
+ );
+ $this->parser->parse_string($template, $data);
+
+ // Result: Hello, John {initials} Doe
+
+If you provide a string substitution parameter when an array is expected,
+i.e. for a variable pair, the substitution is done for the opening variable
+pair tag, but the closing variable pair tag is not rendered properly::
+
+ $template = 'Hello, {firstname} {lastname} ({degrees}{degree} {/degrees})';
+ $data = array(
+ 'degrees' => 'Mr',
+ 'firstname' => 'John',
+ 'lastname' => 'Doe',
+ 'titles' => array(
+ array('degree' => 'BSc'),
+ array('degree' => 'PhD')
+ )
+ );
+ $this->parser->parse_string($template, $data);
+
+ // Result: Hello, John Doe (Mr{degree} {/degrees})
+
+If you name one of your individual substitution parameters the same as one
+used inside a variable pair, the results may not be as expected::
+
+ $template = 'Hello, {firstname} {lastname} ({degrees}{degree} {/degrees})';
+ $data = array(
+ 'degree' => 'Mr',
+ 'firstname' => 'John',
+ 'lastname' => 'Doe',
+ 'degrees' => array(
+ array('degree' => 'BSc'),
+ array('degree' => 'PhD')
+ )
+ );
+ $this->parser->parse_string($template, $data);
+
+ // Result: Hello, John Doe (Mr Mr )
+
+View Fragments
+==============
+
+You do not have to use variable pairs to get the effect of iteration in
+your views. It is possible to use a view fragment for what would be inside
+a variable pair, and to control the iteration in your controller instead
+of in the view.
+
+An example with the iteration controlled in the view::
+
+ $template = '<ul>{menuitems}
+ <li><a href="{link}">{title}</a></li>
+ {/menuitems}</ul>';
+
+ $data = array(
+ 'menuitems' => array(
+ array('title' => 'First Link', 'link' => '/first'),
+ array('title' => 'Second Link', 'link' => '/second'),
+ )
+ );
+ $this->parser->parse_string($template, $data);
+
+Result::
+
+ <ul>
+ <li><a href="/first">First Link</a></li>
+ <li><a href="/second">Second Link</a></li>
+ </ul>
+
+An example with the iteration controlled in the controller,
+using a view fragment::
+
+ $temp = '';
+ $template1 = '<li><a href="{link}">{title}</a></li>';
+ $data1 = array(
+ array('title' => 'First Link', 'link' => '/first'),
+ array('title' => 'Second Link', 'link' => '/second'),
+ );
+
+ foreach ($data1 as $menuitem)
+ {
+ $temp .= $this->parser->parse_string($template1, $menuitem, TRUE);
+ }
+
+ $template = '<ul>{menuitems}</ul>';
+ $data = array(
+ 'menuitems' => $temp
+ );
+ $this->parser->parse_string($template, $data);
+
+Result::
+
+ <ul>
+ <li><a href="/first">First Link</a></li>
+ <li><a href="/second">Second Link</a></li>
+ </ul>
+
***************
Class Reference
***************
@@ -167,8 +296,8 @@ Class Reference
:returns: Parsed template string
:rtype: string
- This method works exactly like ``parse()``, only it accepts the template as a
- string instead of loading a view file.
+ This method works exactly like ``parse()``, only it accepts
+ the template as a string instead of loading a view file.
.. method:: set_delimiters([$l = '{'[, $r = '}']])
@@ -176,4 +305,5 @@ Class Reference
:param string $r: Right delimiter
:rtype: void
- Sets the delimiters (opening and closing) for a value "tag" in a template. \ No newline at end of file
+ Sets the delimiters (opening and closing) for a
+ pseudo-variable "tag" in a template. \ No newline at end of file
diff --git a/user_guide_src/source/libraries/security.rst b/user_guide_src/source/libraries/security.rst
index 0c51e342b..a39ef5976 100644
--- a/user_guide_src/source/libraries/security.rst
+++ b/user_guide_src/source/libraries/security.rst
@@ -12,8 +12,9 @@ application, processing input data for security.
<div class="custom-index container"></div>
+*************
XSS Filtering
-=============
+*************
CodeIgniter comes with a Cross Site Scripting Hack prevention filter
which can either run automatically to filter all POST and COOKIE data
@@ -57,8 +58,9 @@ browser may attempt to execute.
// file failed the XSS test
}
+*********************************
Cross-site request forgery (CSRF)
-=================================
+*********************************
You can enable CSRF protection by altering your **application/config/config.php**
file in the following way::
diff --git a/user_guide_src/source/libraries/sessions.rst b/user_guide_src/source/libraries/sessions.rst
index f05f86af1..6395c0622 100644
--- a/user_guide_src/source/libraries/sessions.rst
+++ b/user_guide_src/source/libraries/sessions.rst
@@ -1,13 +1,20 @@
-##############
-Session Driver
-##############
+###############
+Session Library
+###############
The Session class permits you maintain a user's "state" and track their
-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.
+activity while they browse your site.
+
+CodeIgniter comes with a few session storage drivers:
+
+ - files (default; file-system based)
+ - database
+ - redis
+ - memcached
+
+In addition, you may create your own, custom session drivers based on other
+kinds of storage, while still taking advantage of the features of the
+Session class.
.. contents::
:local:
@@ -23,122 +30,132 @@ Using 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/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
-initializing the class will cause it to read, create, and update
-sessions.
+Sessions will typically run globally with each page load, so the Session
+class should either be initialized 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 initializing the class will cause it to read, create, and update
+sessions when necessary.
To initialize the Session class manually in your controller constructor,
-use the ``$this->load->driver`` function::
+use the ``$this->load->library()`` method::
- $this->load->driver('session');
+ $this->load->library('session');
Once loaded, the Sessions library object will be available using::
$this->session
+.. important:: Because the :doc:`Loader Class </libraries/loader>` is instantiated
+ by CodeIgniter's base controller, make sure to call
+ ``parent::__construct()`` before trying to load a library from
+ inside a controller constructor.
+
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. 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.
+session cookie is sent by the user's browser. If a sessions cookie does
+**not** exist (or if it doesn't match one stored on the server or has
+expired) a new session will be created and saved.
+
+If a valid session does exist, its information will be updated. With each
+update, the session ID may be regenerated if configured to do so.
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
-above behavior to happen. You can, as you'll see below, work with
-session data or even add your own data to a user's session, but the
-process of reading, writing, and updating a session is automatic.
+above behavior to happen. You can, as you'll see below, work with session
+data, but the process of reading, writing, and updating a session is
+automatic.
+
+.. note:: Under CLI, the Session library will automatically halt itself,
+ as this is a concept based entirely on the HTTP protocol.
What is Session Data?
=====================
-A *session*, as far as CodeIgniter is concerned, is simply an array
-containing the following information:
-
-- The user's unique Session ID (this is a statistically random string
- with very strong entropy, hashed with MD5 for portability, and
- regenerated (by default) every five minutes)
-- The user's IP Address
-- The user's User Agent data (the first 120 characters of the browser
- data string)
-- The "last activity" time stamp.
-
-The above data is stored in a cookie as a serialized array with this
-prototype::
-
- [array]
- (
- 'session_id' => random hash,
- 'ip_address' => 'string - user IP address',
- 'user_agent' => 'string - user agent data',
- 'last_activity' => timestamp
- )
-
-.. 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.
+Session data is simply an array associated with a particular session ID
+(cookie).
+
+If you've used sessions in PHP before, you should be familiar with PHP's
+`$_SESSION superglobal <http://php.net/manual/en/reserved.variables.session.php>`_
+(if not, please read the content on that link).
+
+CodeIgniter gives access to its session data through the same means, as it
+uses the session handlers' mechanism provided by PHP. Using session data is
+as simple as manipulating (read, set and unset values) the ``$_SESSION``
+array.
+
+In addition, CodeIgniter also provides 2 special types of session data
+that are further explained below: flashdata and tempdata.
+
+.. note:: In previous versions, regular session data in CodeIgniter was
+ referred to as 'userdata'. Have this in mind if that term is used
+ elsewhere in the manual. Most of it is written to explain how
+ the custom 'userdata' methods work.
Retrieving Session Data
=======================
-Any piece of information from the session array is available using the
-following function::
+Any piece of information from the session array is available through the
+``$_SESSION`` superglobal::
+
+ $_SESSION['item']
+
+Or through the magic getter::
+
+ $this->session->item
+
+And for backwards compatibility, through the ``userdata()`` method::
$this->session->userdata('item');
-Where item is the array index corresponding to the item you wish to
-fetch. For example, to fetch the session ID you will do this::
+Where item is the array key corresponding to the item you wish to fetch.
+For example, to assign a previously stored 'name' item to the ``$name``
+variable, you will do this::
+
+ $name = $_SESSION['name'];
+
+ // or:
- $session_id = $this->session->userdata('session_id');
+ $name = $this->session->name
-.. note:: The function returns NULL if the item you are
- trying to access does not exist.
+ // or:
+
+ $name = $this->session->userdata('name');
+
+.. note:: The ``userdata()`` method returns NULL if the item you are trying
+ to access does not exist.
If you want to retrieve all of the existing userdata, you can simply
-omit the item key parameter::
+omit the item key (magic getter only works for properties)::
- $this->session->userdata();
+ $_SESSION
- /**
- * Produces something similar to:
- *
- * Array
- * (
- * [session_id] => 4a5a5dca22728fb0a84364eeb405b601
- * [ip_address] => 127.0.0.1
- * [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
- * [last_activity] => 1303142623
- * )
- */
-
-Adding Custom Session Data
-==========================
+ // or:
+
+ $this->session->userdata();
-A useful aspect of the session array is that you can add your own data
-to it and it will be stored in the user's cookie. Why would you want to
-do this? Here's one example:
+Adding Session Data
+===================
Let's say a particular user logs into your site. Once authenticated, you
-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.
+could add their username and e-mail address to the session, making that
+data globally available to you without having to run a database query when
+you need it.
+
+You can simply assign data to the ``$_SESSION`` array, as with any other
+variable. Or as a property of ``$this->session``.
-To add your data to the session array involves passing an array
-containing your new data to this function::
+Alternatively, the old method of assigning it as "userdata" is also
+available. That however passing an array containing your new data to the
+``set_userdata()`` method::
$this->session->set_userdata($array);
-Where $array is an associative array containing your new data. Here's an
-example::
+Where ``$array`` is an associative array containing your new data. Here's
+an example::
$newdata = array(
'username' => 'johndoe',
@@ -149,68 +166,104 @@ example::
$this->session->set_userdata($newdata);
If you want to add userdata one value at a time, ``set_userdata()`` also
-supports this syntax.
-
-::
+supports this syntax::
$this->session->set_userdata('some_name', 'some_value');
-If you want to verify that a userdata value exists, call ``has_userdata()``.
+If you want to verify that a session value exists, simply check with
+``isset()``::
-::
+ // returns FALSE if the 'some_name' item doesn't exist or is NULL,
+ // TRUE otherwise:
+ isset($_SESSION['some_name'])
+
+Or you can call ``has_userdata()``::
$this->session->has_userdata('some_name');
Removing Session Data
=====================
-Just as set_userdata() can be used to add information into a session,
-unset_userdata() can be used to remove it, by passing the session key.
-For example, if you wanted to remove 'some_name' from your session
-information::
+Just as with any other variable, unsetting a value in ``$_SESSION`` can be
+done through ``unset()``::
- $this->session->unset_userdata('some_name');
+ unset($_SESSION['some_name']);
+ // or multiple values:
-This function can also be passed an associative array of items to unset.
+ unset(
+ $_SESSION['some_name'],
+ $_SESSION['another_name']
+ );
-::
+Also, just as ``set_userdata()`` can be used to add information to a
+session, ``unset_userdata()`` can be used to remove it, by passing the
+session key. For example, if you wanted to remove 'some_name' from your
+session data array::
+
+ $this->session->unset_userdata('some_name');
+
+This method also accepts an associative array of items to unset::
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
-
Flashdata
=========
CodeIgniter supports "flashdata", or session data that will only be
-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").
+available for the next request, and is then automatically cleared.
+
+This can be very useful, especially for one-time informational, error or
+status messages (for example: "Record 2 deleted").
+
+It should be noted that flashdata variables are regular session vars,
+only marked in a specific way under the '__ci_vars' key (please don't touch
+that one, you've been warned).
-.. note:: Flash variables are prefaced with "flash\_" so avoid this prefix
- in your own session names.
+To mark an existing item as "flashdata"::
+
+ $this->session->mark_as_flash('item');
+
+If you want to mark multiple items as flashdata, simply pass the keys as an
+array::
+
+ $this->session->mark_as_flash(array('item', 'item2'));
To add flashdata::
- $this->session->set_flashdata('item', 'value');
+ $_SESSION['item'] = 'value';
+ $this->session->mark_as_flash('item');
+Or alternatively, using the ``set_flashdata()`` method::
+
+ $this->session->set_flashdata('item', 'value');
You can also pass an array to ``set_flashdata()``, in the same manner as
``set_userdata()``.
-To read a flashdata variable::
+Reading flashdata variables is the same as reading regular session data
+through ``$_SESSION``::
+
+ $_SESSION['item']
+
+.. important:: The ``userdata()`` method will NOT return flashdata items.
+
+However, if you want to be sure that you're reading "flashdata" (and not
+any other kind), you can also use the ``flashdata()`` method::
$this->session->flashdata('item');
-An array of all flashdata can be retrieved as follows::
+Or to get an array with all flashdata, simply omit the key parameter::
$this->session->flashdata();
+.. note:: The ``flashdata()`` method returns NULL if the item cannot be
+ found.
If you find that you need to preserve a flashdata variable through an
-additional request, you can do so using the ``keep_flashdata()`` function.
+additional request, you can do so using the ``keep_flashdata()`` method.
You can either pass a single item or an array of flashdata items to keep.
::
@@ -218,8 +271,6 @@ You can either pass a single item or an array of flashdata items to keep.
$this->session->keep_flashdata('item');
$this->session->keep_flashdata(array('item1', 'item2', 'item3'));
-.. note:: The function will return NULL if the item cannot be found.
-
Tempdata
========
@@ -227,22 +278,56 @@ 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::
- $expire = 300; // Expire in 5 minutes
+ $_SESSION['item'] = 'value';
+ $this->session->mark_as_temp('item', 300); // Expire in 5 minutes
- $this->session->set_tempdata('item', 'value', $expire);
+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, '', $expire);
+ $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::
-.. note:: If the expiration is omitted or set to 0, the default expiration of
- 5 minutes will be used.
+ $_SESSION['item']
-To read a tempdata variable::
+.. important:: The ``userdata()`` method will NOT return tempdata items.
+
+Or if you want to be sure that you're reading "flashdata" (and not any
+other kind), you can also use the ``tempdata()`` method::
$this->session->tempdata('item');
@@ -250,453 +335,675 @@ And of course, if you want to retrieve all existing tempdata::
$this->session->tempdata();
-If you need to remove a tempdata value before it expires,
-use ``unset_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');
Destroying a Session
====================
-To clear the current session::
+To clear the current session (for example, during a logout), you may
+simply use either PHP's `session_destroy() <http://php.net/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 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()``.
+.. 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.
+
+Accessing session metadata
+==========================
+
+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!
Session Preferences
===================
+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** 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. Setting it to 0 will disable session
- ID regeneartion.
-**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.
-=========================== =============== =========================== ==========================================================================
+**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_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_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.
+======================== =============== ======================================== ============================================================================================
+
+.. 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 :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
-=========================== =============== ==========================================================================
+================== =============== ===========================================================================
+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. Additionaly, the 'cookie_prefix' setting is completely
+ ignored.
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
-to validate it. For some applications that require little or no
-security, session ID validation may not be needed, but if your
-application requires security, validation is mandatory. Otherwise, an
-old session could be restored by a user modifying their cookies.
-
-When session data is available in a database, every time a valid session
-is found in the user's cookie, a database query is performed to match
-it. If the session ID does not match, the session is destroyed. Session
-IDs can never be updated, they can only be generated when a new session
-is created.
-
-In order to store sessions, you must first create a database table for
-this purpose. Here is the basic prototype (for MySQL) required by the
-session class::
-
- CREATE TABLE IF NOT EXISTS `ci_sessions` (
- session_id varchar(40) DEFAULT '0' NOT NULL,
- ip_address varchar(45) DEFAULT '0' NOT NULL,
- user_agent varchar(120) NOT NULL,
- last_activity int(10) unsigned DEFAULT 0 NOT NULL,
- user_data text NOT NULL,
- PRIMARY KEY (session_id, ip_address, user_agent),
- KEY `last_activity_idx` (`last_activity`)
+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.
+
+Files 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
+<http://php.net/manual/en/session.configuration.php#ini.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
+0600 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 0600 /<path to your application directory>/sessions/
+ chown www-data /<path to your application directory>/sessions/
+
+Bonus Tip
+^^^^^^^^^
+
+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 <http://eddmann.com/posts/storing-php-sessions-file-caches-in-memory-using-tmpfs/>`_,
+(warning: external resource), which can make your sessions blazing fast.
+
+Database Driver
+---------------
+
+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 can NOT use a persistent connection.
+ - You must have the :doc:`Query Builder </database/query_builder>`
+ 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(40) NOT NULL,
+ `ip_address` varchar(45) NOT NULL,
+ `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
+ `data` blob DEFAULT '' NOT NULL,
+ PRIMARY KEY (id),
+ KEY `ci_sessions_timestamp` (`timestamp`)
);
-Or if you're using PostgreSQL::
+For PostgreSQL::
- CREATE TABLE ci_sessions (
- session_id varchar(40) DEFAULT '0' NOT NULL,
- ip_address varchar(45) DEFAULT '0' NOT NULL,
- user_agent varchar(120) NOT NULL,
- last_activity bigint DEFAULT 0 NOT NULL,
- user_data text NOT NULL,
- PRIMARY KEY (session_id)
+ CREATE TABLE "ci_sessions" (
+ "id" varchar(40) NOT NULL,
+ "ip_address" varchar(45) NOT NULL,
+ "timestamp" bigint DEFAULT 0 NOT NULL,
+ "data" text DEFAULT '' NOT NULL,
+ PRIMARY KEY ("id")
);
- CREATE INDEX last_activity_idx ON ci_sessions(last_activity);
+ CREATE INDEX "ci_sessions_timestamp" ON "ci_sessions" ("timestamp");
+
+However, if you want to turn on the *sess_match_ip* setting, you should
+also do the following, after creating the table::
+
+ // Works both on MySQL and PostgreSQL
+ ALTER TABLE ci_sessions ADD CONSTRAINT ci_sessions_id_ip UNIQUE (id, ip_address);
+
+.. 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.
+
+Redis Driver
+------------
+
+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 <https://github.com/nicolasff/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.
-.. note:: By default the table is called ci_sessions, but you can name
- it anything you want as long as you update the
- *application/config/config.php* file so that it contains the name
- you have chosen. Once you have created your database table you
- can enable the database option in your config.php file as follows::
+For the most common case however, a simple ``host:port`` pair should be
+sufficient::
- $config['sess_use_database'] = TRUE;
+ $config['sess_driver'] = 'redis';
+ $config['sess_save_path'] = 'tcp://localhost:6379';
- Once enabled, the Session class will store session data in the DB.
+Memcached Driver
+----------------
- Make sure you've specified the table name in your config file as well::
+The 'memcached' driver is very similar to the 'redis' one in all of its
+properties, except perhaps for availability, because PHP's `Memcached
+<http://php.net/memcached>`_ extension is distributed via PECL and some
+Linux distrubutions make it available as an easy to install package.
- $config['sess_table_name'] = 'ci_sessions';
+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.
-.. 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.
+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.
-Native Driver
--------------
+The ``$config['sess_save_path']`` format is fairly straightforward here,
+being just a ``host:port`` pair::
-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.
+ $config['sess_driver'] = 'memcached';
+ $config['sess_save_path'] = 'localhost:11211';
+
+Bonus Tip
+^^^^^^^^^
+
+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';
Custom Drivers
--------------
-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.
+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
+:doc:`Creating Libraries <../general/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*.
-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::
+ - Extend the ``CI_Session_driver`` class.
- class CI_Session_custom extends CI_Session_driver {
+ 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.
- protected function initialize()
+
+ - Implement the `SessionHandlerInterface
+ <http://php.net/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)
{
- // Read existing session data or create a new one
+ // Initialize storage mechanism (connection)
}
- public function sess_save()
+ public function read($session_id)
{
- // Save current data to storage
+ // Read session data (if exists), acquire locks
}
- public function sess_destroy()
+ public function write($session_id, $session_data)
{
- // Destroy the current session and clean up storage
+ // Create / update session data (it might not exist!)
}
- public function sess_regenerate()
+ public function close()
{
- // Create new session ID
+ // Free locks, close connections / streams / etc.
}
- public function &get_userdata()
+ public function destroy($session_id)
{
- // Return a reference to your userdata array
+ // Call close() method & destroy data for current session (order may differ)
+ }
+
+ public function gc($maxlifetime)
+ {
+ // Erase data for expired sessions
}
}
-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.
+If you've done everything properly, you can now set your *sess_driver*
+configuration value to 'dummy' and use your own driver. Congratulations!
+
+***************
+Class Reference
+***************
-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::
+.. class:: CI_Session
- CI_Session_foo in libraries/Session/drivers/Session_foo.php
+ .. method:: userdata([$key = NULL])
-Then specify the driver by setting 'sess_driver' in your config.php file or as a
-parameter when loading the CI_Session object::
+ :param mixed $key: Session item key or NULL
+ :returns: Value of the specified item key, or an array of all userdata
+ :rtype: mixed
- $config['sess_driver'] = 'foo';
+ 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.
-OR::
+ .. method:: all_userdata()
- $CI->load->driver('session', array('sess_driver' => 'foo'));
+ :returns: An array of all userdata
+ :rtype: array
-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::
+ Returns an array containing all "userdata" items.
- $config['sess_valid_drivers'] = array('sess_driver');
+ .. note:: This method is DEPRECATED. Use ``userdata()``
+ with no parameters instead.
-***************
-Class Reference
-***************
+ .. method:: &get_usedata()
-.. class:: CI_Session
+ :returns: A reference to ``$_SESSION``
+ :rtype: array
- .. method:: load_driver($driver)
+ Returns a reference to the ``$_SESSION`` array.
- :param string $driver: Driver name
- :returns: Instance of currently loaded session driver
- :rtype: mixed
+ .. note:: This is a legacy method kept only for backwards
+ compatibility with older applications.
- Loads a session storage driver
+ .. method:: has_userdata($key)
- .. method:: select_driver($driver)
+ :param string $key: Session item key
+ :returns: TRUE if the specified key exists, FALSE if not
+ :rtype: bool
- :param string $driver: Driver name
- :rtype: void
+ Checks if an item exists in ``$_SESSION``.
- Selects default session storage driver.
+ .. 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.
- .. method:: sess_destroy()
+ .. method:: set_userdata($data[, $value = NULL])
+ :param mixed $data: An array of key/value pairs to set as session data, or the key for a single item
+ :param mixed $value: The value to set for a specific session item, if $data is a key
:rtype: void
- Destroys current session
+ Assigns data to the ``$_SESSION`` superglobal.
- .. note:: This method should be the last one called, and even flash
- variables will no longer be available after it is used.
- If you only want some items destroyed and not all, use
- ``unset_userdata()``.
+ .. note:: This is a legacy method kept only for backwards
+ compatibility with older applications.
- .. method:: sess_regenerate([$destroy = FALSE])
+ .. method:: unset_userdata($key)
- :param bool $destroy: Whether to destroy session data
+ :param mixed $key: Key for the session data item to unset, or an array of multiple keys
:rtype: void
- Regenerate the current session data.
+ Unsets the specified key(s) from the ``$_SESSION``
+ superglobal.
- .. method:: userdata([$item = NULL])
-
- :param string $item: Session item name
- :returns: Item value if found, NULL if not or an array of all userdata if $item parameter is not used
- :rtype: mixed
+ .. 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.
- If no parameter is passed, it will return an associative array of all existing userdata.
+ .. method:: mark_as_flash($key)
- Otherwise returns a string containing the value of the passed item or NULL if the item is not found.
- Example::
+ :param mixed $key: Key to mark as flashdata, or an array of multiple keys
+ :returns: TRUE on success, FALSE on failure
+ :rtype: bool
- $this->session->userdata('user');
- //returns example@example.com considering the set_userdata example.
+ Marks a ``$_SESSION`` item key (or multiple ones) as
+ "flashdata".
- .. method:: all_userdata()
+ .. method:: get_flash_keys()
- :returns: An array of all userdata
+ :returns: Array containing the keys of all "flashdata" items.
:rtype: array
- Returns an array with all of the session userdata items.
+ Gets a list of all ``$_SESSION`` that have been marked as
+ "flashdata".
- .. note:: This method is DEPRECATED. Use ``userdata()`` with no parameters instead.
+ .. method:: umark_flash($key)
- .. method:: &get_userdata()
+ :param mixed $key: Key to be un-marked as flashdata, or an array of multiple keys
+ :rtype: void
- :returns: A reference to the userdata array
- :rtype: &array
+ Unmarks a ``$_SESSION`` item key (or multiple ones) as
+ "flashdata".
- Returns a reference to the userdata array.
+ .. method:: flashdata([$key = NULL])
- .. method:: set_userdata($newdata[, $newval = ''])
+ :param mixed $key: Flashdata item key or NULL
+ :returns: Value of the specified item key, or an array of all flashdata
+ :rtype: mixed
- :param mixed $newdata: Item name or array of items
- :param mixed $newval: Item value or empty string (not required if $newdata is array)
- :rtype: void
+ 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.
- Sets items into session example usages::
+ .. method:: keep_flashdata($key)
- $this->session->set_userdata('user', 'example@example.com');
- // adds item user with value example@example.com to the session
+ :param mixed $key: Flashdata key to keep, or an array of multiple keys
+ :returns: TRUE on success, FALSE on failure
+ :rtype: bool
- $this->session->set_userdata(array('user'=>'example@example.com'));
- // does the same as the above example - adds item user with value example@example.com to the session
+ Retains the specified session data key(s) as "flashdata"
+ through the next request.
- .. method:: unset_userdata($item)
+ .. 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.
- :param mixed $item: Item name or an array containing multiple items
- :rtype: void
+ .. method:: set_flashdata($data[, $value = NULL])
- Unsets previously set items from the session. Example::
+ :param mixed $data: An array of key/value pairs to set as flashdata, or the key for a single item
+ :param mixed $value: The value to set for a specific session item, if $data is a key
+ :rtype: void
- $this->session->unset_userdata('user');
- //unsets 'user' from session data.
+ Assigns data to the ``$_SESSION`` superglobal and marks it
+ as "flashdata".
- $this->session->unset_userdata(array('user', 'useremail'));
- //unsets both 'user' and 'useremail' from the session data.
+ .. note:: This is a legacy method kept only for backwards
+ compatibility with older applications.
- .. method:: has_userdata($item)
+ .. method:: mark_as_temp($key[, $ttl = 300])
- :param string $item: Item name
- :returns: TRUE if item exists, FALSE if not
+ :param mixed $key: Key to mark as tempdata, or an array of multiple keys
+ :param int $ttl: Time-to-live value for the tempdata, in seconds
+ :returns: TRUE on success, FALSE on failure
:rtype: bool
- Checks if an item exists in the session.
-
- .. method:: flashdata([$item = NULL])
+ Marks a ``$_SESSION`` item key (or multiple ones) as
+ "tempdata".
- :param string $item: Flashdata item name
- :returns: Item value if found, NULL if not or an array of all flashdata if $item parameter is not used
- :rtype: mixed
+ .. method:: get_temp_keys()
- If no parameter is passed, it will return an associative array of all existing flashdata.
+ :returns: Array containing the keys of all "tempdata" items.
+ :rtype: array
- Otherwise returns a string containing the value of the passed item or NULL if the item is not found.
- Example::
+ Gets a list of all ``$_SESSION`` that have been marked as
+ "tempdata".
- $this->session->flashdata('message');
- //returns 'Test message.' considering the set_flashdata example.
+ .. method:: umark_temp($key)
- .. method:: set_flashdata($newdata[, $newval = ''])
+ :param mixed $key: Key to be un-marked as tempdata, or an array of multiple keys
+ :rtype: void
- :param mixed $newdata: Item name or an array of items
- :param mixed $newval: Item value or empty string (not required if $newdata is array)
- :rtype: void
+ Unmarks a ``$_SESSION`` item key (or multiple ones) as
+ "tempdata".
- Sets items into session flashdata example usages::
+ .. method:: tempdata([$key = NULL])
- $this->session->set_flashdata('message', 'Test message.');
- // adds item 'message' with value 'Test message.' to the session flashdata
+ :param mixed $key: Tempdata item key or NULL
+ :returns: Value of the specified item key, or an array of all tempdata
+ :rtype: mixed
- $this->session->set_flashdata(array('message'=>'Test message.'));
- // does the same as the above example - adds item 'message' with value 'Test message.'
- to the session flashdata
+ 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.
- .. method:: keep_flashdata($item)
+ .. method:: set_tempdata($data[, $value = NULL])
- :param mixed $item: Item name or an array containing multiple flashdata items
+ :param mixed $data: An array of key/value pairs to set as tempdata, or the key for a single item
+ :param mixed $value: The value to set for a specific session item, if $data is a key
+ :param int $ttl: Time-to-live value for the tempdata item(s), in seconds
:rtype: void
- Keeps items into flashdata for one more request.
+ Assigns data to the ``$_SESSION`` superglobal and marks it
+ as "tempdata".
- .. method:: tempdata([$item = NULL])
+ .. note:: This is a legacy method kept only for backwards
+ compatibility with older applications.
- :param string $item: Tempdata item name
- :returns: Item value if found, NULL if not or an array of all tempdata if $item parameter is not used
- :rtype: mixed
+ .. method:: sess_regenerate([$destroy = FALSE])
- If no parameter is passed, it will return an associative array of all existing tempdata.
+ :param bool $destroy: Whether to destroy session data
+ :rtype: void
- Otherwise returns a string containing the value of the passed item or NULL if the item is not found.
- Example::
+ Regenerate session ID, optionally destroying the current
+ session's data.
- $this->session->tempdata('message');
- //returns 'Test message.' considering the set_tempdata example.
+ .. note:: This method is just an alias for PHP's native
+ `session_regenerate_id()
+ <http://php.net/session_regenerate_id>`_ function.
- .. method:: set_tempdata($newdata[, $newval = ''[, $expire = 0]])
+ .. method:: sess_destroy()
- :param mixed $newdata: Item name or array containing multiple items
- :param string $newval: Item value or empty string (not required if $newdata is array)
- :param int $expire: Lifetime in seconds (0 for default)
:rtype: void
- Sets items into session tempdata example::
+ Destroys the current session.
- $this->session->set_tempdata('message', 'Test message.', '60');
- // adds item 'message' with value 'Test message.' to the session tempdata for 60 seconds
+ .. note:: This must be the *last* session-related function
+ that you call. All session data will be lost after
+ you do that.
- $this->session->set_tempdata(array('message'=>'Test message.'));
- // does the same as the above example - adds item 'message' with value 'Test message.'
- to the session tempdata for the default value of
+ .. note:: This method is just an alias for PHP's native
+ `session_destroy()
+ <http://php.net/session_destroy>`_ function.
- .. method:: unset_tempdata($item)
+ .. method:: __get($key)
- :param mixed $item: Item name or an array containing multiple items
- :rtype: void
+ :param string $key: Session item key
+ :returns: The requested session data item, or NULL if it doesn't exist
+ :rtype: 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``.
+
+ .. method:: __set($key, $value)
+
+ :param string $key: Session item key
+ :param mixed $value: Value to assign to the session item key
+ :returns: void
- Unsets previously set items from tempdata. Example::
+ A magic method that allows you to assign items to
+ ``$_SESSION`` by accessing them as ``$this->session``
+ properties::
- $this->session->unset_tempdata('user');
- //unsets 'user' from tempdata.
+ $this->session->foo = 'bar';
- $this->session->unset_tempdata(array('user', 'useremail'));
- //unsets both 'user' and 'useremail' from the tempdata. \ No newline at end of file
+ // Results in:
+ // $_SESSION['foo'] = 'bar'; \ No newline at end of file
diff --git a/user_guide_src/source/libraries/trackback.rst b/user_guide_src/source/libraries/trackback.rst
index 22859a13d..da7c319ac 100644
--- a/user_guide_src/source/libraries/trackback.rst
+++ b/user_guide_src/source/libraries/trackback.rst
@@ -67,7 +67,7 @@ Description of array data:
- **blog_name** - The name of your weblog.
- **charset** - The character encoding your weblog is written in. If omitted, UTF-8 will be used.
-.. note:: the Trackback class will automatically send only the first 500 characters of your
+.. note:: The Trackback class will automatically send only the first 500 characters of your
entry. It will also strip all HTML.
The Trackback sending method returns TRUE/FALSE (boolean) on success
diff --git a/user_guide_src/source/libraries/unit_testing.rst b/user_guide_src/source/libraries/unit_testing.rst
index 0bc860f61..7e91a7b95 100644
--- a/user_guide_src/source/libraries/unit_testing.rst
+++ b/user_guide_src/source/libraries/unit_testing.rst
@@ -18,6 +18,10 @@ code to determine if it is producing the correct data type and result.
<div class="custom-index container"></div>
+******************************
+Using the Unit Testing Library
+******************************
+
Initializing the Class
======================
diff --git a/user_guide_src/source/libraries/zip.rst b/user_guide_src/source/libraries/zip.rst
index 4ca14086a..ce70e6c88 100644
--- a/user_guide_src/source/libraries/zip.rst
+++ b/user_guide_src/source/libraries/zip.rst
@@ -2,9 +2,8 @@
Zip Encoding Class
##################
-CodeIgniter's Zip Encoding Class classes permit you to create Zip
-archives. Archives can be downloaded to your desktop or saved to a
-directory.
+CodeIgniter's Zip Encoding Class permits you to create Zip archives.
+Archives can be downloaded to your desktop or saved to a directory.
.. contents::
:local:
@@ -25,7 +24,9 @@ your controller using the $this->load->library function::
$this->load->library('zip');
-Once loaded, the Zip library object will be available using: $this->zip
+Once loaded, the Zip library object will be available using:
+
+ $this->zip
Usage Example
=============
@@ -41,7 +42,7 @@ your server, and download it to your desktop.
$this->zip->add_data($name, $data);
// Write the zip file to a folder on your server. Name it "my_backup.zip"
- $this->zip->archive('/path/to/directory/my_backup.zip');
+ $this->zip->archive('/path/to/directory/my_backup.zip');
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
@@ -52,6 +53,14 @@ Class Reference
.. class:: CI_Zip
+ .. attribute:: $compression_level = 2
+
+ The compression level to use.
+
+ It can range from 0 to 9, with 9 being the highest and 0 effectively disabling compression::
+
+ $this->zip->compression_level = 0;
+
.. method:: add_data($filepath[, $data = NULL])
:param mixed $filepath: A single file path or an array of file => data pairs
@@ -60,7 +69,8 @@ Class Reference
Adds data to the Zip archive. Can work both in single and multiple files mode.
- When adding a single file, the first parameter must contain the name you would like given to the file and the second must contain the file contents::
+ When adding a single file, the first parameter must contain the name you would
+ like given to the file and the second must contain the file contents::
$name = 'mydata1.txt';
$data = 'A Data String!';
@@ -69,8 +79,9 @@ Class Reference
$name = 'mydata2.txt';
$data = 'Another Data String!';
$this->zip->add_data($name, $data);
-
- When adding multiple files, the first parameter must contain *file => contents* pairs and the second parameter is ignored::
+
+ When adding multiple files, the first parameter must contain *file => contents* pairs
+ and the second parameter is ignored::
$data = array(
'mydata1.txt' => 'A Data String!',
@@ -79,7 +90,8 @@ Class Reference
$this->zip->add_data($data);
- If you would like your compressed data organized into sub-directories, simply include the path as part of the filename(s)::
+ If you would like your compressed data organized into sub-directories, simply include
+ the path as part of the filename(s)::
$name = 'personal/my_bio.txt';
$data = 'I was born in an elevator...';
@@ -93,8 +105,9 @@ Class Reference
:param mixed $directory: Directory name string or an array of multiple directories
:rtype: void
- Permits you to add a directory. Usually this method is unnecessary since you can place your data into directories when using
- ``$this->zip->add_data()``, but if you would like to create an empty directory you can do so::
+ Permits you to add a directory. Usually this method is unnecessary since you can place
+ your data into directories when using ``$this->zip->add_data()``, but if you would like
+ to create an empty directory you can do so::
$this->zip->add_dir('myfolder'); // Creates a directory called "myfolder"
@@ -110,7 +123,7 @@ Class Reference
$path = '/path/to/photo.jpg';
- $this->zip->read_file($path);
+ $this->zip->read_file($path);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
@@ -120,7 +133,7 @@ Class Reference
$path = '/path/to/photo.jpg';
- $this->zip->read_file($path, TRUE);
+ $this->zip->read_file($path, TRUE);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
@@ -151,20 +164,21 @@ Class Reference
$path = '/path/to/your/directory/';
- $this->zip->read_dir($path);
+ $this->zip->read_dir($path);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
- By default the Zip archive will place all directories listed in the first parameter inside the zip.
- If you want the tree preceding the target directory to be ignored you can pass FALSE (boolean) in the second parameter. Example::
+ By default the Zip archive will place all directories listed in the first parameter
+ inside the zip. If you want the tree preceding the target directory to be ignored,
+ you can pass FALSE (boolean) in the second parameter. Example::
$path = '/path/to/your/directory/';
$this->zip->read_dir($path, FALSE);
- This will create a ZIP with a directory named "directory" inside, then all sub-directories stored correctly inside that, but will not include the
- */path/to/your* part of the path.
+ This will create a ZIP with a directory named "directory" inside, then all sub-directories
+ stored correctly inside that, but will not include the */path/to/your* part of the path.
.. method:: archive($filepath)
@@ -172,8 +186,9 @@ Class Reference
:returns: TRUE on success, FALSE on failure
:rtype: bool
- Writes the Zip-encoded file to a directory on your server. Submit a valid server path ending in the file name.
- Make sure the directory is writable (755 is usually OK). Example::
+ Writes the Zip-encoded file to a directory on your server. Submit a valid server path
+ ending in the file name. Make sure the directory is writable (755 is usually OK).
+ Example::
$this->zip->archive('/path/to/folder/myarchive.zip'); // Creates a file named myarchive.zip
@@ -182,7 +197,8 @@ Class Reference
:param string $filename: Archive file name
:rtype: void
- Causes the Zip file to be downloaded from your server. You must pass the name you would like the zip file called. Example::
+ Causes the Zip file to be downloaded from your server.
+ You must pass the name you would like the zip file called. Example::
$this->zip->download('latest_stuff.zip'); // File will be named "latest_stuff.zip"
@@ -195,7 +211,8 @@ Class Reference
:returns: Zip file content
:rtype: string
- Returns the Zip-compressed file data. Generally you will not need this method unless you want to do something unique with the data. Example::
+ Returns the Zip-compressed file data. Generally you will not need this method unless you
+ want to do something unique with the data. Example::
$name = 'my_bio.txt';
$data = 'I was born in an elevator...';
@@ -208,8 +225,9 @@ Class Reference
:rtype: void
- The Zip class caches your zip data so that it doesn't need to recompile the Zip archive for each method you use above.
- If, however, you need to create multiple Zip archives, each with different data, you can clear the cache between calls. Example::
+ The Zip class caches your zip data so that it doesn't need to recompile the Zip archive
+ for each method you use above. If, however, you need to create multiple Zip archives,
+ each with different data, you can clear the cache between calls. Example::
$name = 'my_bio.txt';
$data = 'I was born in an elevator...';
@@ -217,9 +235,9 @@ Class Reference
$this->zip->add_data($name, $data);
$zip_file = $this->zip->get_zip();
- $this->zip->clear_data();
+ $this->zip->clear_data();
$name = 'photo.jpg';
$this->zip->read_file("/path/to/photo.jpg"); // Read the file's contents
- $this->zip->download('myphotos.zip'); \ No newline at end of file
+ $this->zip->download('myphotos.zip');