diff options
author | Eric Roberts <eric@cryode.com> | 2012-12-12 14:02:11 +0100 |
---|---|---|
committer | Eric Roberts <eric@cryode.com> | 2012-12-12 14:02:11 +0100 |
commit | b9e35f21e1c70b6aa67c47e9244ed83195abc00a (patch) | |
tree | 64f82db362deeac48cc20d1d1afd80651f36f5a5 /user_guide_src/source/libraries | |
parent | 0b05705c52c3bca7f9b3aee657c888e8ad1ff422 (diff) | |
parent | 545a7c86701875e1412bcde316e9bcc76d9a23a0 (diff) |
Merge branch 'refs/heads/develop' into feature/form_error_msgs
Conflicts:
system/language/english/form_validation_lang.php
user_guide_src/source/libraries/form_validation.rst
Signed-off-by: Eric Roberts <eric@cryode.com>
Diffstat (limited to 'user_guide_src/source/libraries')
23 files changed, 1090 insertions, 482 deletions
diff --git a/user_guide_src/source/libraries/caching.rst b/user_guide_src/source/libraries/caching.rst index 2f06d29f9..8d7b4c440 100644 --- a/user_guide_src/source/libraries/caching.rst +++ b/user_guide_src/source/libraries/caching.rst @@ -32,6 +32,17 @@ available in the hosting environment. echo $foo; +You can also prefix cache item names via the **key_prefix** setting, which is useful +to avoid collisions when you're running multiple applications on the same environment. + +:: + + $this->load->driver('cache', + array('adapter' => 'apc', 'backup' => 'file', 'key_prefix' => 'my_') + ); + + $this->cache->get('foo'); // Will get the cache entry named 'my_foo' + ****************** Function Reference ****************** @@ -39,7 +50,7 @@ Function Reference .. php:class:: CI_Cache is_supported() -=============== +============== .. php:method:: is_supported ( $driver ) @@ -130,7 +141,7 @@ clean() $this->cache->clean(); cache_info() -============= +============ .. php:method:: cache_info ( ) @@ -148,7 +159,7 @@ cache_info() get_metadata() -=============== +============== .. php:method:: get_metadata ( $id ) @@ -166,7 +177,6 @@ get_metadata() .. note:: The information returned and the structure of the data is dependent on which adapter is being used. - ******* Drivers ******* @@ -181,7 +191,7 @@ specific adapter to the driver loader as follows:: $this->cache->apc->save('foo', 'bar', 10); For more information on APC, please see -`http://php.net/apc <http://php.net/apc>`_ +`http://php.net/apc <http://php.net/apc>`_. File-based Caching ================== @@ -201,20 +211,49 @@ Memcached Caching ================= Multiple Memcached servers can be specified in the memcached.php -configuration file, located in the application/config/ directory. +configuration file, located in the _application/config/* directory. -All of the functions listed above can be accessed without passing a +All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:: $this->load->driver('cache'); $this->cache->memcached->save('foo', 'bar', 10); For more information on Memcached, please see -`http://php.net/memcached <http://php.net/memcached>`_ +`http://php.net/memcached <http://php.net/memcached>`_. + +WinCache Caching +================ + +Under Windows, you can also utilize the WinCache driver. + +All of the functions listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->wincache->save('foo', 'bar', 10); + +For more information on WinCache, please see +`http://php.net/wincache <http://php.net/wincache>`_. + +Redis Caching +============= + +All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->redis->save('foo', 'bar', 10); + +.. important:: Redis may require one or more of the following options: + **host**, **post**, **timeout**, **password**. + +The Redis PHP extension repository is located at +`https://github.com/nicolasff/phpredis <https://github.com/nicolasff/phpredis>`_. Dummy Cache =========== This is a caching backend that will always 'miss.' It stores no data, but lets you keep your caching code in place in environments that don't -support your chosen cache. +support your chosen cache.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/cart.rst b/user_guide_src/source/libraries/cart.rst index 6594b3b9a..716e94bcb 100644 --- a/user_guide_src/source/libraries/cart.rst +++ b/user_guide_src/source/libraries/cart.rst @@ -279,16 +279,22 @@ by which this is returned by passing it "true" where the contents will be sorted from newest to oldest, by leaving this function blank, you'll automatically just get first added to the basket to last added to the basket. -$this->cart->has_options(rowid); -******************************** +$this->cart->get_item($row_id); +******************************* + +Returns an array containing data for the item matching the specified row ID, +or FALSE if no such item exists. + +$this->cart->has_options($row_id); +********************************** Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above. -$this->cart->product_options(rowid); -************************************ +$this->cart->product_options($row_id); +************************************** Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart->contents(), since you diff --git a/user_guide_src/source/libraries/config.rst b/user_guide_src/source/libraries/config.rst index c81cad7b3..08d9c2905 100644 --- a/user_guide_src/source/libraries/config.rst +++ b/user_guide_src/source/libraries/config.rst @@ -149,11 +149,13 @@ folders: - Your own custom configuration files .. note:: - CodeIgniter always tries to load the configuration files for - the current environment first. If the file does not exist, the global - config file (i.e., the one in application/config/) is loaded. This means - you are not obligated to place **all** of your configuration files in an - environment folder − only the files that change per environment. + CodeIgniter always loads the global config file first (i.e., the one in application/config/), + then tries to load the configuration files for the current environment. + This means you are not obligated to place **all** of your configuration files in an + environment folder. Only the files that change per environment. Additionally you don't + have to copy **all** the config items in the environment config file. Only the config items + that you wish to change for your environment. The config items declared in your environment + folders always overwrite those in your global config files. Helper Functions ================ diff --git a/user_guide_src/source/libraries/email.rst b/user_guide_src/source/libraries/email.rst index daf000907..8643444f8 100644 --- a/user_guide_src/source/libraries/email.rst +++ b/user_guide_src/source/libraries/email.rst @@ -97,7 +97,7 @@ Preference Default Value Options Descript **mailtype** text text or html Type of mail. If you send HTML email you must send it as a complete web page. Make sure you don't have any relative links or relative image paths otherwise they will not work. -**charset** utf-8 Character set (utf-8, iso-8859-1, etc.). +**charset** ``$config['charset']`` Character set (utf-8, iso-8859-1, etc.). **validate** FALSE TRUE or FALSE (boolean) Whether to validate the email address. **priority** 3 1, 2, 3, 4, 5 Email Priority. 1 = highest. 5 = lowest. 3 = normal. **crlf** \\n "\\r\\n" or "\\n" or "\\r" Newline character. (Use "\\r\\n" to comply with RFC 822). @@ -117,6 +117,13 @@ Sets the email address and name of the person sending the email:: $this->email->from('you@example.com', 'Your Name'); +You can also set a Return-Path, to help redirect undelivered mail:: + + $this->email->from('you@example.com', 'Your Name', 'returned_emails@example.com'); + +.. note:: Return-Path can't be used if you've configured + 'smtp' as your protocol. + $this->email->reply_to() ------------------------- @@ -182,6 +189,14 @@ formatting which is added to the header string for people who do not accept HTML email. If you do not set your own message CodeIgniter will extract the message from your HTML email and strip the tags. +$this->email->set_header() +-------------------------- + +Appends additional headers to the e-mail:: + + $this->email->set_header('Header1', 'Value1'); + $this->email->set_header('Header2', 'Value2'); + $this->email->clear() --------------------- @@ -218,6 +233,14 @@ success or failure, enabling it to be used conditionally:: // Generate error } +This function will automatically clear all parameters if the request was +successful. To stop this behaviour pass FALSE:: + + if ($this->email->send(FALSE)) + { + // Parameters won't be cleared + } + $this->email->attach() ---------------------- @@ -245,11 +268,21 @@ parameter as mime-type:: $this->email->attach($buffer, 'attachment', 'report.pdf', 'application/pdf'); $this->email->print_debugger() -------------------------------- +------------------------------ Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging. +You can optionally specify which parts of the message should be printed. +Valid options are: **headers**, **subject**, **body**. + +Example:: + + // Will only print the email headers, excluding the message subject and body + $this->email->print_debugger(array('headers')); + +.. note:: By default, all of the raw data will be printed. + Overriding Word Wrapping ======================== diff --git a/user_guide_src/source/libraries/encryption.rst b/user_guide_src/source/libraries/encryption.rst index 28bdca203..a38122203 100644 --- a/user_guide_src/source/libraries/encryption.rst +++ b/user_guide_src/source/libraries/encryption.rst @@ -26,7 +26,7 @@ key security so you may want to think carefully before using it for anything that requires high security, like storing credit card numbers. To take maximum advantage of the encryption algorithm, your key should -be 32 characters in length (128 bits). The key should be as random a +be 32 characters in length (256 bits). The key should be as random a string as you can concoct, with numbers and uppercase and lowercase letters. Your key should **not** be a simple text string. In order to be cryptographically secure it needs to be as random as possible. diff --git a/user_guide_src/source/libraries/file_uploading.rst b/user_guide_src/source/libraries/file_uploading.rst index d573fc770..c7965ae11 100644 --- a/user_guide_src/source/libraries/file_uploading.rst +++ b/user_guide_src/source/libraries/file_uploading.rst @@ -26,7 +26,7 @@ Creating the Upload Form ======================== Using a text editor, create a form called upload_form.php. In it, place -this code and save it to your applications/views/ folder:: +this code and save it to your **application/views/** directory:: <html> <head> @@ -59,7 +59,7 @@ The Success Page ================ Using a text editor, create a form called upload_success.php. In it, -place this code and save it to your applications/views/ folder:: +place this code and save it to your **application/views/** directory:: <html> <head> @@ -84,7 +84,7 @@ The Controller ============== Using a text editor, create a controller called upload.php. In it, place -this code and save it to your applications/controllers/ folder:: +this code and save it to your **application/controllers/** directory:: <?php @@ -127,12 +127,12 @@ this code and save it to your applications/controllers/ folder:: } ?> -The Upload Folder -================= +The Upload Directory +==================== -You'll need a destination folder for your uploaded images. Create a -folder at the root of your CodeIgniter installation called uploads and -set its file permissions to 777. +You'll need a destination directory for your uploaded images. Create a +directory at the root of your CodeIgniter installation called uploads +and set its file permissions to 777. Try it! ======= @@ -153,7 +153,7 @@ Initializing the Upload Class ============================= Like most other classes in CodeIgniter, the Upload class is initialized -in your controller using the $this->load->library function:: +in your controller using the ``$this->load->library()`` method:: $this->load->library('upload'); @@ -175,7 +175,7 @@ following preferences:: $this->load->library('upload', $config); - // Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class: + // Alternately you can set preferences by calling the ``initialize()`` method. Useful if you auto-load the class: $this->upload->initialize($config); The above preferences should be fairly self-explanatory. Below is a @@ -190,22 +190,27 @@ what will be used if you do not specify that preference. ============================ ================= ======================= ====================================================================== Preference Default Value Options Description ============================ ================= ======================= ====================================================================== -**upload_path** None None The path to the folder where the upload should be placed. The folder - must be writable and the path can be absolute or relative. +**upload_path** None None The path to the directory where the upload should be placed. The + directory must be writable and the path can be absolute or relative. **allowed_types** None None The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Separate multiple types with a pipe. **file_name** None Desired file name If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. + If no extension is provided in the original file_name will be used. **overwrite** FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists. **max_size** 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default. -**max_width** 0 None The maximum width (in pixels) that the file can be. Set to zero for no +**max_width** 0 None The maximum width (in pixels) that the image can be. Set to zero for no limit. -**max_height** 0 None The maximum height (in pixels) that the file can be. Set to zero for no +**max_height** 0 None The maximum height (in pixels) that the image can be. Set to zero for no + limit. +**min_width** 0 None The minimum width (in pixels) that the image can be. Set to zero for no + limit. +**min_height** 0 None The minimum height (in pixels) that the image can be. Set to zero for no limit. **max_filename** 0 None The maximum length that a file name can be. Set to zero for no limit. **max_filename_increment** 100 None When overwrite is set to FALSE, use this to set the maximum filename @@ -215,6 +220,9 @@ Preference Default Value Options Descripti that can not be discerned by the person uploading it. **remove_spaces** TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to underscores. This is recommended. +**detect_mime** TRUE TRUE/FALSE (boolean) If set to TRUE, a server side detection of the file type will be + performed to avoid code injection attacks. DO NOT disable this option + unless you have no other option as that would cause a security risk. ============================ ================= ======================= ====================================================================== Setting preferences in a config file @@ -223,42 +231,46 @@ Setting preferences in a config file If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the upload.php, add the $config array in that file. Then save the file in: -config/upload.php and it will be used automatically. You will NOT need -to use the $this->upload->initialize function if you save your +**config/upload.php** and it will be used automatically. You will NOT +need to use the ``$this->upload->initialize()`` method if you save your preferences in a config file. -****************** -Function Reference -****************** +*************** +Class Reference +*************** -The following functions are available +The following methods are available: $this->upload->do_upload() -=========================== +========================== -Performs the upload based on the preferences you've set. Note: By -default the upload routine expects the file to come from a form field -called userfile, and the form must be a "multipart type:: +Performs the upload based on the preferences you've set. + +.. note:: By default the upload routine expects the file to come from + a form field called userfile, and the form must be of type + "multipart". + +:: <form method="post" action="some_action" enctype="multipart/form-data" /> If you would like to set your own field name simply pass its value to -the do_upload function:: +the ``do_upload()`` method:: $field_name = "some_field_name"; $this->upload->do_upload($field_name); $this->upload->display_errors() -================================ +=============================== -Retrieves any error messages if the do_upload() function returned -false. The function does not echo automatically, it returns the data so +Retrieves any error messages if the ``do_upload()`` method returned +false. The method does not echo automatically, it returns the data so you can assign it however you need. Formatting Errors ***************** -By default the above function wraps any errors within <p> tags. You can +By default the above method wraps any errors within <p> tags. You can set your own delimiters like this:: $this->upload->display_errors('<p>', '</p>'); @@ -266,27 +278,31 @@ set your own delimiters like this:: $this->upload->data() ===================== -This is a helper function that returns an array containing all of the +This is a helper method that returns an array containing all of the data related to the file you uploaded. Here is the array prototype:: Array ( - [file_name] => mypic.jpg - [file_type] => image/jpeg - [file_path] => /path/to/your/upload/ - [full_path] => /path/to/your/upload/jpg.jpg - [raw_name] => mypic - [orig_name] => mypic.jpg - [client_name] => mypic.jpg - [file_ext] => .jpg - [file_size] => 22.2 - [is_image] => 1 - [image_width] => 800 - [image_height] => 600 - [image_type] => jpeg - [image_size_str] => width="800" height="200" + [file_name] => mypic.jpg + [file_type] => image/jpeg + [file_path] => /path/to/your/upload/ + [full_path] => /path/to/your/upload/jpg.jpg + [raw_name] => mypic + [orig_name] => mypic.jpg + [client_name] => mypic.jpg + [file_ext] => .jpg + [file_size] => 22.2 + [is_image] => 1 + [image_width] => 800 + [image_height] => 600 + [image_type] => jpeg + [image_size_str] => width="800" height="200" ) +To return one element from the array:: + + $this->upload->data('file_name'); // Returns: mypic.jpg + Explanation *********** @@ -324,4 +340,4 @@ Image height Image type. Typically the file extension without the period. **image_size_str** A string containing the width and height. Useful to put into an image -tag. +tag.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst index 9ff2d0eb3..acf1e5619 100644 --- a/user_guide_src/source/libraries/form_validation.rst +++ b/user_guide_src/source/libraries/form_validation.rst @@ -63,7 +63,7 @@ The Form ======== Using a text editor, create a form called myform.php. In it, place this -code and save it to your applications/views/ folder:: +code and save it to your application/views/ folder:: <html> <head> @@ -98,7 +98,7 @@ The Success Page ================ Using a text editor, create a form called formsuccess.php. In it, place -this code and save it to your applications/views/ folder:: +this code and save it to your application/views/ folder:: <html> <head> @@ -117,7 +117,7 @@ The Controller ============== Using a text editor, create a controller called form.php. In it, place -this code and save it to your applications/controllers/ folder:: +this code and save it to your application/controllers/ folder:: <?php @@ -252,30 +252,30 @@ Setting Rules Using an Array Before moving on it should be noted that the rule setting function can be passed an array if you prefer to set all your rules in one action. If -you use this approach you must name your array keys as indicated:: +you use this approach, you must name your array keys as indicated:: $config = array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'Password Confirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ); + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); $this->form_validation->set_rules($config); @@ -286,10 +286,9 @@ CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules in the third parameter of rule setting function, like this:: $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]'); - $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]'); - $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); + $this->form_validation->set_rules('password', 'Password', 'required'); + $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]'); - The above code sets the following rules: @@ -302,6 +301,10 @@ Give it a try! Submit your form without the proper data and you'll see new error messages that correspond to your new rules. There are numerous rules available which you can read about in the validation reference. +.. note:: You can also pass an array of rules to set_rules(), instead of a string. Example:: + + $this->form_validation->set_rules('username', 'Username', array('required', 'min_length[5]')); + Prepping Data ============= @@ -310,8 +313,8 @@ 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('password', 'Password', 'trim|required|matches[passconf]|md5'); - $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required'); + $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 @@ -393,7 +396,7 @@ The validation system supports callbacks to your own validation functions. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback function -that does that. Let's create a example of this. +that does that. Let's create an example of this. In your controller, change the "username" rule to this:: @@ -431,7 +434,7 @@ Here's how your controller should now look:: { if ($str == 'test') { - $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); + $this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"'); return FALSE; } else @@ -463,7 +466,7 @@ Setting Error Messages ====================== All of the native error messages are located in the following language -file: system/language/english/form_validation_lang.php +file: /system/language/english/form_validation_lang.php To set your own custom message you can either edit that file, or use the following function:: @@ -473,7 +476,7 @@ following function:: Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed. -If you'd like to include a field's "human" name or the optional +If you'd like to include a field's "human" name, or the optional parameter some rules allow for (such as max_length), you can add the **{field}** and **{param}** tags to your message, respectively. @@ -486,16 +489,11 @@ error would display: "Username must have at least 5 characters." still work, however it will override the tags above. You should use one or the other. -In the "callback" example above, the error message was set by passing -the name of the function:: +In the callback rule example above, the error message was set by passing +the name of the function (without the "callback_" prefix):: $this->form_validation->set_message('username_check') -You can also override any error message found in the language file. For -example, to change the message for the "required" rule you will do this:: - - $this->form_validation->set_message('required', 'Your custom message here'); - .. _translating-field-names: Translating Field Names @@ -552,11 +550,10 @@ globally, individually, or change the defaults in a config file. #. **Set delimiters in a config file** You can add your error delimiters in application/config/form_validation.php as follows:: - + $config['error_prefix'] = '<div class="error_prefix">'; $config['error_suffix'] = '</div>'; - Showing Errors Individually =========================== @@ -584,8 +581,8 @@ Try it! Change your form so that it looks like this:: If there are no errors, nothing will be shown. If there is an error, the message will appear. -.. note:: **Important Note:** If you use an array as the name of a form field, you -must supply it as an array to the function. Example:: +.. important:: If you use an array as the name of a form field, you + must supply it as an array to the function. Example:: <?php echo form_error('options[size]'); ?> <input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /> @@ -595,20 +592,20 @@ For more info please see the :ref:`using-arrays-as-field-names` section below. Validating an Array (other than $_POST) ======================================= -Sometimes you may want to validate an array that does not originate from $_POST data. +Sometimes you may want to validate an array that does not originate from ``$_POST`` data. In this case, you can specify the array to be validated:: - + $data = array( - 'username' => 'johndoe', - 'password' => 'mypassword', - 'passconf' => 'mypassword' - ); + 'username' => 'johndoe', + 'password' => 'mypassword', + 'passconf' => 'mypassword' + ); $this->form_validation->set_data($data); -Creating validation rules, running the validation and retrieving error messages works the same whether you are -validating $_POST data or an array. +Creating validation rules, running the validation, and retrieving error messages works the +same whether you are validating ``$_POST`` data or an array. **Important Note:** If you want to validate more than one array during a single execution, then you should call the reset_validation() function before setting up rules and validating the new array. @@ -636,32 +633,32 @@ you will place an array named $config with your rules. As shown earlier, the validation array will have this prototype:: $config = array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'Password Confirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ); + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); Your validation rule file will be loaded automatically and used when you -call the run() function. +call the ``run()`` method. -Please note that you MUST name your array $config. +Please note that you MUST name your ``$config`` array. Creating Sets of Rules ====================== @@ -672,121 +669,121 @@ rules. We've arbitrarily called these two rules "signup" and "email". You can name your rules anything you want:: $config = array( - 'signup' => array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'PasswordConfirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ), - 'email' => array( - array( - 'field' => 'emailaddress', - 'label' => 'EmailAddress', - 'rules' => 'required|valid_email' - ), - array( - 'field' => 'name', - 'label' => 'Name', - 'rules' => 'required|alpha' - ), - array( - 'field' => 'title', - 'label' => 'Title', - 'rules' => 'required' - ), - array( - 'field' => 'message', - 'label' => 'MessageBody', - 'rules' => 'required' - ) - ) - ); + 'signup' => array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ), + 'email' => array( + array( + 'field' => 'emailaddress', + 'label' => 'EmailAddress', + 'rules' => 'required|valid_email' + ), + array( + 'field' => 'name', + 'label' => 'Name', + 'rules' => 'required|alpha' + ), + array( + 'field' => 'title', + 'label' => 'Title', + 'rules' => 'required' + ), + array( + 'field' => 'message', + 'label' => 'MessageBody', + 'rules' => 'required' + ) + ) + ); Calling a Specific Rule Group ============================= -In order to call a specific group you will pass its name to the run() -function. For example, to call the signup rule you will do this:: +In order to call a specific group, you will pass its name to the ``run()`` +method. For example, to call the signup rule you will do this:: if ($this->form_validation->run('signup') == FALSE) { - $this->load->view('myform'); + $this->load->view('myform'); } else { - $this->load->view('formsuccess'); + $this->load->view('formsuccess'); } Associating a Controller Function with a Rule Group =================================================== An alternate (and more automatic) method of calling a rule group is to -name it according to the controller class/function you intend to use it +name it according to the controller class/method you intend to use it with. For example, let's say you have a controller named Member and a -function named signup. Here's what your class might look like:: +method named signup. Here's what your class might look like:: <?php class Member extends CI_Controller { - function signup() - { - $this->load->library('form_validation'); - - if ($this->form_validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } - } + function signup() + { + $this->load->library('form_validation'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } } In your validation config file, you will name your rule group member/signup:: $config = array( - 'member/signup' => array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'PasswordConfirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ) - ); + 'member/signup' => array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'PasswordConfirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ) + ); When a rule group is named identically to a controller class/function it will be used automatically when the run() function is invoked from that @@ -863,8 +860,10 @@ Rule Parameter Description ========================= ========== ============================================================================================= ======================= **required** No Returns FALSE if the form element is empty. **matches** Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item] -**is_unique** Yes Returns FALSE if the form element is not unique to the is_unique[table.field] - table and field name in the parameter. is_unique[table.field] +**differs** Yes Returns FALSE if the form element does not differ from the one in the parameter. differs[form_item] +**is_unique** Yes Returns FALSE if the form element is not unique to the table and field name in the is_unique[table.field] + parameter. Note: This rule requires :doc:`Query Builder <../database/query_builder>` to be + enabled in order to work. **max_length** Yes Returns FALSE if the form element is longer then the parameter value. max_length[12] **exact_length** Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8] **greater_than** Yes Returns FALSE if the form element is less than or equal to the parameter value or not greater_than[8] @@ -886,10 +885,11 @@ Rule Parameter Description 0, 1, 2, 3, etc. **is_natural_no_zero** No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc. -**is_unique** Yes Returns FALSE if the form element is not unique in a database table. is_unique[table.field] +**valid_url** No Returns FALSE if the form element does not contain a valid URL. **valid_email** No Returns FALSE if the form element does not contain a valid email address. **valid_emails** No Returns FALSE if any value provided in a comma separated list is not a valid email. **valid_ip** No Returns FALSE if the supplied IP is not valid. + Accepts an optional parameter of 'ipv4' or 'ipv6' to specify an IP format. **valid_base64** No Returns FALSE if the supplied string contains anything other than valid Base64 characters. ========================= ========== ============================================================================================= ======================= @@ -919,8 +919,8 @@ Name Parameter Description **encode_php_tags** No Converts PHP tags to entities. ==================== ========= =================================================================================================== -.. note:: You can also use any native PHP functions that permit one - parameter, like trim, htmlspecialchars, urldecode, etc. +.. note:: You can also use any native PHP functions that permits one + parameter, like ``trim()``, ``htmlspecialchars()``, ``urldecode()``, etc. .. _function-reference: @@ -934,15 +934,15 @@ The following functions are intended for use in your controller functions. $this->form_validation->set_rules(); -====================================== +==================================== .. php:method:: set_rules ($field, $label = '', $rules = '') :param string $field: The field name :param string $label: The field label - :param string $rules: The rules, seperated by a pipe "|" + :param mixed $rules: The rules, as a string with rules separated by a pipe "|", or an array or rules. :rtype: Object - + Permits you to set validation rules, as described in the tutorial sections above: @@ -950,19 +950,19 @@ $this->form_validation->set_rules(); - :ref:`saving-groups` $this->form_validation->run(); -=============================== +============================== .. php:method:: run ($group = '') :param string $group: The name of the validation group to run :rtype: Boolean - + Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via the function, as described in: :ref:`saving-groups` $this->form_validation->set_message(); -======================================== +====================================== .. php:method:: set_message ($lang, $val = '') @@ -973,7 +973,7 @@ $this->form_validation->set_message(); Permits you to set custom error messages. See :ref:`setting-error-messages` $this->form_validation->set_data(); -======================================== +=================================== .. php:method:: set_data ($data = '') @@ -985,13 +985,13 @@ $this->form_validation->set_data(); $this->form_validation->reset_validation(); =========================================== - .. php:method:: reset_validation () + .. php:method:: reset_validation () - Permits you to reset the validation when you validate more than one array. - This function should be called before validating each new array. + Permits you to reset the validation when you validate more than one array. + This method should be called before validating each new array. $this->form_validation->error_array(); -======================================== +====================================== .. php:method:: error_array () @@ -1010,7 +1010,7 @@ containing your forms. Note that these are procedural functions, so they **do not** require you to prepend them with $this->form_validation. form_error() -============= +============ Shows an individual error message associated with the field name supplied to the function. Example:: @@ -1021,7 +1021,7 @@ The error delimiters can be optionally specified. See the :ref:`changing-delimiters` section above. validation_errors() -==================== +=================== Shows all error messages as a string: Example:: @@ -1031,7 +1031,7 @@ The error delimiters can be optionally specified. See the :ref:`changing-delimiters` section above. set_value() -============ +=========== Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The @@ -1043,7 +1043,7 @@ form. Example:: The above form will show "0" when loaded for the first time. set_select() -============= +============ If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter must contain the name @@ -1060,7 +1060,7 @@ Example:: </select> set_checkbox() -=============== +============== Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second @@ -1071,7 +1071,7 @@ lets you set an item as the default (use boolean TRUE/FALSE). Example:: <input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> /> set_radio() -============ +=========== Permits you to display radio buttons in the state they were submitted. This function is identical to the **set_checkbox()** function above. diff --git a/user_guide_src/source/libraries/ftp.rst b/user_guide_src/source/libraries/ftp.rst index 20b11a5c8..05a3fdcc8 100644 --- a/user_guide_src/source/libraries/ftp.rst +++ b/user_guide_src/source/libraries/ftp.rst @@ -26,7 +26,7 @@ Usage Examples In this example a connection is opened to the FTP server, and a local file is read and uploaded in ASCII mode. The file permissions are set to -755. Note: Setting permissions requires PHP 5. +755. :: @@ -136,8 +136,7 @@ Example:: **Mode options are:** ascii, binary, and auto (the default). If auto is used it will base the mode on the file extension of the source file. -Permissions are available if you are running PHP 5 and can be passed as -an octal value in the fourth parameter. +If set, permissions have to be passed as an octal value. $this->ftp->download() ====================== diff --git a/user_guide_src/source/libraries/image_lib.rst b/user_guide_src/source/libraries/image_lib.rst index ed6575c62..dcdccbd92 100644 --- a/user_guide_src/source/libraries/image_lib.rst +++ b/user_guide_src/source/libraries/image_lib.rst @@ -91,9 +91,9 @@ error upon failure, like this:: echo $this->image_lib->display_errors(); } -Note: You can optionally specify the HTML formatting to be applied to -the errors, by submitting the opening/closing tags in the function, like -this:: +.. note:: You can optionally specify the HTML formatting to be applied to + the errors, by submitting the opening/closing tags in the function, + like this:: $this->image_lib->display_errors('<p>', '</p>'); @@ -225,8 +225,7 @@ pixels) specifying where to crop, like this:: $config['y_axis'] = '40'; All preferences listed in the table above are available for this -function except these: rotation_angle, width, height, create_thumb, -new_image. +function except these: rotation_angle, create_thumb, new_image. Here's an example showing how you might crop an image:: @@ -243,11 +242,11 @@ Here's an example showing how you might crop an image:: echo $this->image_lib->display_errors(); } -Note: Without a visual interface it is difficult to crop images, so this -function is not very useful unless you intend to build such an -interface. That's exactly what we did using for the photo gallery module -in ExpressionEngine, the CMS we develop. We added a JavaScript UI that -lets the cropping area be selected. +.. note:: Without a visual interface it is difficult to crop images, so this + function is not very useful unless you intend to build such an + interface. That's exactly what we did using for the photo gallery module + in ExpressionEngine, the CMS we develop. We added a JavaScript UI that + lets the cropping area be selected. $this->image_lib->rotate() =========================== @@ -338,8 +337,8 @@ The above example will use a 16 pixel True Type font to create the text bottom/center of the image, 20 pixels from the bottom of the image. .. note:: In order for the image class to be allowed to do any - processing, the image file must have "write" file permissions. For - example, 777. + processing, the image file must have "write" file permissions + For example, 777. Watermarking Preferences ======================== diff --git a/user_guide_src/source/libraries/input.rst b/user_guide_src/source/libraries/input.rst index 1f2ea650a..177f5cb64 100644 --- a/user_guide_src/source/libraries/input.rst +++ b/user_guide_src/source/libraries/input.rst @@ -5,8 +5,7 @@ Input Class The Input Class serves two purposes: #. It pre-processes global input data for security. -#. It provides some helper functions for fetching input data and - pre-processing it. +#. It provides some helper methods for fetching input data and pre-processing it. .. note:: This class is initialized automatically by the system so there is no need to do it manually. @@ -14,11 +13,11 @@ The Input Class serves two purposes: Security Filtering ================== -The security filtering function is called automatically when a new +The security filtering method is called automatically when a new :doc:`controller <../general/controllers>` is invoked. It does the following: -- If $config['allow_get_array'] is FALSE(default is TRUE), destroys +- If $config['allow_get_array'] is FALSE (default is TRUE), destroys the global GET array. - Destroys all global variables in the event register_globals is turned on. @@ -42,33 +41,27 @@ this:: Please refer to the :doc:`Security class <security>` documentation for information on using XSS Filtering in your application. -Using POST, COOKIE, or SERVER Data -================================== +Using POST, GET, COOKIE, or SERVER Data +======================================= -CodeIgniter comes with three helper functions that let you fetch POST, +CodeIgniter comes with four helper methods that let you fetch POST, GET, COOKIE or SERVER items. The main advantage of using the provided -functions rather than fetching an item directly ($_POST['something']) -is that the functions will check to see if the item is set and return -false (boolean) if not. This lets you conveniently use data without +methods rather than fetching an item directly (``$_POST['something']``) +is that the methods will check to see if the item is set and return +NULL if not. This lets you conveniently use data without having to test whether an item exists first. In other words, normally you might do something like this:: - if ( ! isset($_POST['something'])) - { - $something = FALSE; - } - else - { - $something = $_POST['something']; - } + $something = isset($_POST['something']) ? $_POST['something'] : NULL; -With CodeIgniter's built in functions you can simply do this:: +With CodeIgniter's built in methods you can simply do this:: $something = $this->input->post('something'); -The three functions are: +The four methods are: - $this->input->post() +- $this->input->get() - $this->input->cookie() - $this->input->server() @@ -80,8 +73,8 @@ looking for:: $this->input->post('some_data'); -The function returns FALSE (boolean) if the item you are attempting to -retrieve does not exist. +The method returns NULL if the item you are attempting to retrieve +does not exist. The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE; @@ -95,7 +88,7 @@ To return an array of all POST items call without any parameters. To return all POST items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean; -The function returns FALSE (boolean) if there are no items in the POST. +The method returns NULL if there are no items in the POST. :: @@ -105,8 +98,8 @@ The function returns FALSE (boolean) if there are no items in the POST. $this->input->get() =================== -This function is identical to the post function, only it fetches get -data:: +This method is identical to the post method, only it fetches get data +:: $this->input->get('some_data', TRUE); @@ -115,7 +108,7 @@ To return an array of all GET items call without any parameters. To return all GET items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean; -The function returns FALSE (boolean) if there are no items in the GET. +The method returns NULL if there are no items in the GET. :: @@ -124,9 +117,9 @@ The function returns FALSE (boolean) if there are no items in the GET. $this->input->get_post() -========================= +======================== -This function will search through both the post and get streams for +This method will search through both the post and get streams for data, looking first in post, and then in get:: $this->input->get_post('some_data', TRUE); @@ -134,24 +127,53 @@ data, looking first in post, and then in get:: $this->input->cookie() ====================== -This function is identical to the post function, only it fetches cookie -data:: +This method is identical to the post method, only it fetches cookie data +:: + + $this->input->cookie('some_cookie'); + $this->input->cookie('some_cookie, TRUE); // with XSS filter - $this->input->cookie('some_data', TRUE); $this->input->server() ====================== -This function is identical to the above functions, only it fetches +This method is identical to the above methods, only it fetches server server data:: $this->input->server('some_data'); +Using the php://input stream +============================ + +If you want to utilize the PUT, DELETE, PATCH or other exotic request +methods, they can only be accessed via a special input stream, that +can only be read once. This isn't as easy as just reading from e.g. +the ``$_POST`` array, because it will always exist and you can try +and access multiple variables without caring that you might only have +one shot at all of the POST data. + +CodeIgniter will take care of that for you, and you can access data +from the **php://input** stream at any time, just by calling the +``input_stream()`` method:: + + $this->input->input_stream('key'); + +Similar to the methods above, if the requested data is not found, it +will return NULL and you can also decide whether to run the data +through ``xss_clean()`` by passing a boolean value as the second +parameter:: + + $this->input->input_stream('key', TRUE); // XSS Clean + $this->input->input_stream('key', FALSE); // No XSS filter + +.. note:: You can utilize method() in order to know if you're reading + PUT, DELETE or PATCH data. + $this->input->set_cookie() -=========================== +========================== Sets a cookie containing the values you specify. There are two ways to -pass information to this function so that a cookie can be set: Array +pass information to this method so that a cookie can be set: Array Method, and Discrete Parameters: Array Method @@ -186,7 +208,7 @@ For site-wide cookies regardless of how your site is requested, add your URL to the **domain** starting with a period, like this: .your-domain.com -The path is usually not needed since the function sets a root path. +The path is usually not needed since the method sets a root path. The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server. @@ -202,41 +224,25 @@ parameters:: $this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); -$this->input->cookie() -====================== - -Lets you fetch a cookie. The first parameter will contain the name of -the cookie you are looking for (including any prefixes):: - - cookie('some_cookie'); - -The function returns FALSE (boolean) if the item you are attempting to -retrieve does not exist. - -The second optional parameter lets you run the data through the XSS -filter. It's enabled by setting the second parameter to boolean TRUE; - -:: - - cookie('some_cookie', TRUE); - $this->input->ip_address() -=========================== +========================== Returns the IP address for the current user. If the IP address is not -valid, the function will return an IP of: 0.0.0.0 +valid, the method will return an IP of: 0.0.0.0 :: echo $this->input->ip_address(); $this->input->valid_ip($ip) -============================ +=========================== Takes an IP address as input and returns TRUE or FALSE (boolean) if it -is valid or not. Note: The $this->input->ip_address() function above -validates the IP automatically. +is valid or not. + +.. note:: The $this->input->ip_address() method above automatically + validates the IP address. :: @@ -249,8 +255,11 @@ validates the IP automatically. echo 'Valid'; } +Accepts an optional second string parameter of 'ipv4' or 'ipv6' to specify +an IP format. The default checks for both formats. + $this->input->user_agent() -=========================== +========================== Returns the user agent (web browser) being used by the current user. Returns FALSE if it's not available. @@ -263,7 +272,7 @@ See the :doc:`User Agent Class <user_agent>` for methods which extract information from the user agent string. $this->input->request_headers() -================================ +=============================== Useful if running in a non-Apache environment where `apache_request_headers() <http://php.net/apache_request_headers>`_ @@ -273,8 +282,8 @@ will not be supported. Returns an array of headers. $headers = $this->input->request_headers(); -$this->input->get_request_header(); -===================================== +$this->input->get_request_header() +================================== Returns a single member of the request headers array. @@ -283,13 +292,13 @@ Returns a single member of the request headers array. $this->input->get_request_header('some-header', TRUE); $this->input->is_ajax_request() -================================= +=============================== Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns a boolean response. $this->input->is_cli_request() -================================ +============================== Checks to see if the STDIN constant is set, which is a failsafe way to see if PHP is being run on the command line. @@ -298,8 +307,8 @@ see if PHP is being run on the command line. $this->input->is_cli_request() -$this->input->method(); -===================================== +$this->input->method() +====================== Returns the $_SERVER['REQUEST_METHOD'], optional set uppercase or lowercase (default lowercase). @@ -307,4 +316,4 @@ Returns the $_SERVER['REQUEST_METHOD'], optional set uppercase or lowercase (def echo $this->input->method(TRUE); // Outputs: POST echo $this->input->method(FALSE); // Outputs: post - echo $this->input->method(); // Outputs: post + echo $this->input->method(); // Outputs: post
\ No newline at end of file diff --git a/user_guide_src/source/libraries/javascript.rst b/user_guide_src/source/libraries/javascript.rst index 5e80fb998..393d4e321 100644 --- a/user_guide_src/source/libraries/javascript.rst +++ b/user_guide_src/source/libraries/javascript.rst @@ -86,14 +86,14 @@ The jQuery Class To initialize the jQuery class manually in your controller constructor, use the $this->load->library function:: - $this->load->library('jquery'); + $this->load->library('javascript/jquery'); You may send an optional parameter to determine whether or not a script tag for the main jQuery file will be automatically included when loading the library. It will be created by default. To prevent this, load the library as follows:: - $this->load->library('jquery', FALSE); + $this->load->library('javascript/jquery', FALSE); Once loaded, the jQuery library object will be available using: $this->jquery @@ -192,7 +192,7 @@ and triggered by a click using the jQuery library's click() event. 'width' => '50%', 'marginLeft' => 125 ); - $this->jquery->click('#trigger', $this->jquery->animate('#note', $params, normal)); + $this->jquery->click('#trigger', $this->jquery->animate('#note', $params, 'normal')); fadeIn() / fadeOut() -------------------- diff --git a/user_guide_src/source/libraries/language.rst b/user_guide_src/source/libraries/language.rst index ec678cd21..d288cd65e 100644 --- a/user_guide_src/source/libraries/language.rst +++ b/user_guide_src/source/libraries/language.rst @@ -10,12 +10,11 @@ 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 folder called language inside your -application folder and store them there. CodeIgniter will look first in -your application/language directory. If the directory does not exist or -the specified language is not located there CI will instead look in your -global system/language folder. +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. .. note:: Each language should be stored in its own folder. For example, the English files are located at: system/language/english @@ -23,14 +22,14 @@ global system/language folder. Creating Language Files ======================= -Language files must be named with _lang.php as the file extension. For +Language files must be named with **_lang.php** as the file extension. For example, let's say you want to create a file containing error messages. You might name it: error_lang.php Within the file you will assign each line of text to an array called -$lang with this prototype:: +``$lang`` with this prototype:: - $lang['language_key'] = "The actual message to be shown"; + $lang['language_key'] = 'The actual message to be shown'; .. note:: It's a good practice to use a common prefix for all messages in a given file to avoid collisions with similarly named items in other @@ -39,9 +38,9 @@ $lang with this prototype:: :: - $lang['error_email_missing'] = "You must submit an email address"; - $lang['error_url_missing'] = "You must submit a URL"; - $lang['error_username_missing'] = "You must submit a username"; + $lang['error_email_missing'] = 'You must submit an email address'; + $lang['error_url_missing'] = 'You must submit a URL'; + $lang['error_username_missing'] = 'You must submit a username'; Loading A Language File ======================= @@ -54,7 +53,9 @@ first. Loading a language file is done with the following code:: Where filename is the name of the file you wish to load (without the 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. +in your **application/config/config.php** file will be used. + +.. note:: The *language* parameter can only consist of letters. Fetching a Line of Text ======================= @@ -64,27 +65,28 @@ text using this function:: $this->lang->line('language_key'); -Where language_key is the array key corresponding to the line you wish +Where *language_key* is the array key corresponding to the line you wish to show. -Note: This function simply returns the line. It does not echo it for -you. +You can optionally pass FALSE as the second argument of that method to +disable error logging, in case you're not sure if the line exists:: + + $this->lang->line('misc_key', FALSE); + +.. note:: This method simply returns the line. It does not echo it. Using language lines as form labels ----------------------------------- This feature has been deprecated from the language library and moved to -the lang() function of the :doc:`Language -helper <../helpers/language_helper>`. +the :php:func:`lang()` function of the :doc:`Language Helper +<../helpers/language_helper>`. Auto-loading Languages ====================== If you find that you need a particular language globally throughout your -application, you can tell CodeIgniter to -:doc:`auto-load <../general/autoloader>` it during system -initialization. This is done by opening the -application/config/autoload.php file and adding the language(s) to the -autoload array. - - +application, you can tell CodeIgniter to :doc:`auto-load +<../general/autoloader>` it during system initialization. This is done +by opening the **application/config/autoload.php** file and adding the +language(s) to the autoload array.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/loader.rst b/user_guide_src/source/libraries/loader.rst index 2090404bf..615aba1c2 100644 --- a/user_guide_src/source/libraries/loader.rst +++ b/user_guide_src/source/libraries/loader.rst @@ -4,6 +4,7 @@ Loader Class Loader, as the name suggests, is used to load elements. These elements can be libraries (classes) :doc:`View files <../general/views>`, +:doc:`Drivers <../general/drivers>`, :doc:`Helpers <../general/helpers>`, :doc:`Models <../general/models>`, or your own files. @@ -74,6 +75,70 @@ Assigning a Library to a different object name If the third (optional) parameter is blank, the library will usually be assigned to an object with the same name as the library. For example, if +the library is named Calendar, it will be assigned to a variable named +$this->calendar. + +If you prefer to set your own class names you can pass its value to the +third parameter:: + + $this->load->library('calendar', '', 'my_calendar'); + + // Calendar class is now accessed using: + + $this->my_calendar + +Please take note, when multiple libraries are supplied in an array for +the first parameter, this parameter is discarded. + +$this->load->driver('parent_name', $config, 'object name') +=========================================================== + +This function is used to load driver libraries. Where parent_name is the +name of the parent class you want to load. + +As an example, if you would like to use sessions with CodeIgniter, the first +step is to load the session driver within your controller:: + + $this->load->driver('session'); + +Once loaded, the library will be ready for use, using +$this->session->*some_function*(). + +Driver files must be stored in a subdirectory within the main +"libraries" folder, or within your personal application/libraries +folder. The subdirectory must match the parent class name. Read the +:doc:`Drivers <../general/drivers>` description for details. + +Additionally, multiple driver libraries can be loaded at the same time by +passing an array of drivers to the load function. + +:: + + $this->load->driver(array('session', 'cache')); + +Setting options +--------------- + +The second (optional) parameter allows you to optionally pass +configuration settings. You will typically pass these as an array:: + + $config = array ( + 'sess_driver' => 'cookie', + 'sess_encrypt_cookie' => true, + 'encryption_key' => 'mysecretkey' + ); + + $this->load->driver('session', $config); + +Config options can usually also be set via a config file. Each library +is explained in detail in its own page, so please read the information +regarding each one you would like to use. + +Assigning a Driver to a different object name +---------------------------------------------- + +If the third (optional) parameter is blank, the library will be assigned +to an object with the same name as the parent class. For example, if the library is named Session, it will be assigned to a variable named $this->session. @@ -86,8 +151,8 @@ third parameter:: $this->my_session -Please take note, when multiple libraries are supplied in an array for -the first parameter, this parameter is discarded. +.. note:: Driver libraries may also be loaded with the library() method, + but it is faster to use driver() $this->load->view('file_name', $data, true/false) ================================================== @@ -116,12 +181,12 @@ assign it to a variable if you want the data returned:: $string = $this->load->view('myfile', '', true); -$this->load->model('Model_name'); +$this->load->model('model_name'); ================================== :: - $this->load->model('Model_name'); + $this->load->model('model_name'); If your model is located in a sub-folder, include the relative path from @@ -134,7 +199,7 @@ application/models/blog/queries.php you'll load it using:: If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function:: - $this->load->model('Model_name', 'fubar'); + $this->load->model('model_name', 'fubar'); $this->fubar->function(); @@ -279,6 +344,6 @@ calling add_package_path(). $this->load->remove_package_path(APPPATH.'my_app'); // Again without the second parameter: - $this->load->add_package_path(APPPATH.'my_app', TRUE); + $this->load->add_package_path(APPPATH.'my_app'); $this->load->view('my_app_index'); // Loads - $this->load->view('welcome_message'); // Loads
\ No newline at end of file + $this->load->view('welcome_message'); // Loads diff --git a/user_guide_src/source/libraries/migration.rst b/user_guide_src/source/libraries/migration.rst index 5192f1f29..1a73fb78d 100644 --- a/user_guide_src/source/libraries/migration.rst +++ b/user_guide_src/source/libraries/migration.rst @@ -2,4 +2,162 @@ Migrations Class ################ -Coming soon.
\ No newline at end of file +Migrations are a convenient way for you to alter your database in a +structured and organized manner. You could edit fragments of SQL by hand +but you would then be responsible for telling other developers that they +need to go and run them. You would also have to keep track of which changes +need to be run against the production machines next time you deploy. + +The database table **migration** tracks which migrations have already been +run so all you have to do is update your application files and +call **$this->migrate->current()** to work out which migrations should be run. +The current version is found in **config/migration.php**. + +******************** +Migration file names +******************** + +Each Migration is run in numeric order forward or backwards depending on the +method taken. Two numbering styles are available: + +* **Sequential:** each migration is numbered in sequence, starting with **001**. + Each number must be three digits, and there must not be any gaps in the + sequence. (This was the numbering scheme prior to CodeIgniter 3.0.) +* **Timestamp:** each migration is numbered using the timestamp when the migration + was created, in **YYYYMMDDHHIISS** format (e.g. **20121031100537**). This + helps prevent numbering conflicts when working in a team environment, and is + the preferred scheme in CodeIgniter 3.0 and later. + +The desired style may be selected using the **$config['migration_type']** +setting in your **migration.php** config file. + +Regardless of which numbering style you choose to use, prefix your migration +files with the migration number followed by an underscore and a descriptive +name for the migration. For example: + +* **001_add_blog.php** (sequential numbering) +* **20121031100537_add_blog.php** (timestamp numbering) + +****************** +Create a Migration +****************** + +This will be the first migration for a new site which has a blog. All +migrations go in the folder **application/migrations/** and have names such +as **20121031100537_add_blog.php**.:: + + <?php + + defined('BASEPATH') OR exit('No direct script access allowed'); + + class Migration_Add_blog extends CI_Migration { + + public function up() + { + $this->dbforge->add_field(array( + 'blog_id' => array( + 'type' => 'INT', + 'constraint' => 5, + 'unsigned' => TRUE, + 'auto_increment' => TRUE + ), + 'blog_title' => array( + 'type' => 'VARCHAR', + 'constraint' => '100', + ), + 'blog_description' => array( + 'type' => 'TEXT', + 'null' => TRUE, + ), + )); + $this->dbforge->add_key('blog_id', TRUE); + $this->dbforge->create_table('blog'); + } + + public function down() + { + $this->dbforge->drop_table('blog'); + } + } + +Then in **application/config/migration.php** set **$config['migration_version'] = 1;**. + +************* +Usage Example +************* + +In this example some simple code is placed in **application/controllers/migrate.php** +to update the schema.:: + + <?php + + class Migrate extends CI_Controller + { + public function index() + { + $this->load->library('migration'); + + if ($this->migration->current() === FALSE) + { + show_error($this->migration->error_string()); + } + } + } + +****************** +Function Reference +****************** + +$this->migration->current() +============================ + +The current migration is whatever is set for **$config['migration_version']** in +**application/config/migration.php**. + +$this->migration->error_string() +================================= + +This returns a string of errors while performing a migration. + +$this->migration->find_migrations() +==================================== + +An array of migration filenames are returned that are found in the **migration_path** +property. + +$this->migration->latest() +=========================== + +This works much the same way as current() but instead of looking for +the **$config['migration_version']** the Migration class will use the very +newest migration found in the filesystem. + +$this->migration->version() +============================ + +Version can be used to roll back changes or step forwards programmatically to +specific versions. It works just like current but ignores **$config['migration_version']**.:: + + $this->load->library('migration'); + + $this->migration->version(5); + +********************* +Migration Preferences +********************* + +The following is a table of all the config options for migrations. + +========================== ====================== ========================== ============================================= +Preference Default Options Description +========================== ====================== ========================== ============================================= +**migration_enabled** FALSE TRUE / FALSE Enable or disable migrations. +**migration_path** APPPATH.'migrations/' None The path to your migrations folder. +**migration_version** 0 None The current version your database should use. +**migration_table** migrations None The table name for storing the schema + version number. +**migration_auto_latest** FALSE TRUE / FALSE Enable or disable automatically + running migrations. +**migration_type** 'timestamp' 'timestamp' / 'sequential' The type of numeric identifier used to name + migration files. +========================== ====================== ========================== ============================================= diff --git a/user_guide_src/source/libraries/output.rst b/user_guide_src/source/libraries/output.rst index baceaae7b..a3d67b847 100644 --- a/user_guide_src/source/libraries/output.rst +++ b/user_guide_src/source/libraries/output.rst @@ -49,17 +49,41 @@ data, JPEG's, XML, etc easily. .. important:: Make sure any non-mime string you pass to this method exists in config/mimes.php or it will have no effect. -$this->output->get_content_type(); -========================================== +You can also set the character set of the document, by passing a second argument:: -Returns the Content-Type HTTP header that's currently in use. + $this->output->set_content_type('css', 'utf-8'); + +$this->output->get_content_type() +================================= + +Returns the Content-Type HTTP header that's currently in use, +excluding the character set value. $mime = $this->output->get_content_type(); .. note:: If not set, the default return value is 'text/html'. -$this->output->get_output(); -============================= +$this->output->get_header() +=========================== + +Gets the requested HTTP header value, if set. + +If the header is not set, NULL will be returned. +If an empty value is passed to the method, it will return FALSE. + +Example:: + + $this->output->set_content_type('text/plain', 'UTF-8'); + echo $this->output->get_header('content-type'); + // Outputs: text/plain; charset=utf-8 + +.. note:: The header name is compared in a case-insensitive manner. + +.. note:: Raw headers sent via PHP's native ``header()`` function are + also detected. + +$this->output->get_output() +=========================== Permits you to manually retrieve any output that has been sent for storage in the output class. Usage example:: @@ -101,6 +125,9 @@ Permits you to manually set a server status header. Example:: `See here <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>`_ for a full list of headers. +.. note:: This method is an alias for :doc:`Common function <../general/common_functions>` + ``set_status_header()``. + $this->output->enable_profiler(); ================================== diff --git a/user_guide_src/source/libraries/pagination.rst b/user_guide_src/source/libraries/pagination.rst index f1653c913..d9d3f5092 100644 --- a/user_guide_src/source/libraries/pagination.rst +++ b/user_guide_src/source/libraries/pagination.rst @@ -21,9 +21,9 @@ Here is a simple example showing how to create pagination in one of your $config['base_url'] = 'http://example.com/index.php/test/page/'; $config['total_rows'] = 200; - $config['per_page'] = 20; + $config['per_page'] = 20; - $this->pagination->initialize($config); + $this->pagination->initialize($config); echo $this->pagination->create_links(); @@ -80,8 +80,8 @@ 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_number'] = 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, @@ -112,6 +112,33 @@ 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; +====================================== + +By default your Query String arguments (nothing to do with other +query string options) will be ignored. Setting this config to +TRUE will add existing query string arguments back into the +URL after the URI segment and before the suffix + +:: + + http://example.com/index.php/test/page/20?query=search%term + +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'] = ''; +================================== + +A custom prefix added to the path. The prefix value will be right before +the offset segment. + +$config['suffix'] = ''; +================================== + +A custom suffix added to the path. The sufix value will be right after +the offset segment. + *********************** Adding Enclosing Markup *********************** @@ -247,10 +274,30 @@ adding:: $config['display_pages'] = FALSE; -****************************** -Adding a class to every anchor -****************************** +**************************** +Adding attributes to anchors +**************************** + +If you want to add an extra attribute to be added to every link rendered +by the pagination class, you can set them as key/value pairs in the +"attributes" config + +:: + + // Produces: class="myclass" + $config['attributes'] = array('class' => 'myclass'); + +.. note:: Usage of the old method of setting classes via "anchor_class" + is deprecated. + +***************************** +Disabling the "rel" attribute +***************************** + +By default the rel attribute is dynamically generated and appended to +the appropriate anchors. If for some reason you want to turn it off, +you can pass boolean FALSE as a regular attribute + +:: -If you want to add a class attribute to every link rendered by the -pagination class, you can set the config "anchor_class" equal to the -classname you want. + $config['attributes']['rel'] = FALSE;
\ 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 e7d25555f..05553142f 100644 --- a/user_guide_src/source/libraries/security.rst +++ b/user_guide_src/source/libraries/security.rst @@ -26,7 +26,7 @@ processing since it requires a fair amount of processing overhead. To filter data through the XSS filter use this function: $this->security->xss_clean() -============================= +============================ Here is an usage example:: @@ -56,7 +56,7 @@ browser may attempt to execute. } $this->security->sanitize_filename() -===================================== +==================================== When accepting filenames from user input, it is best to sanitize them to prevent directory traversal and other security related issues. To do so, @@ -76,16 +76,35 @@ parameter, $relative_path to TRUE. Cross-site request forgery (CSRF) ================================= -You can enable csrf protection by opening your +You can enable CSRF protection by opening your application/config/config.php file and setting this:: $config['csrf_protection'] = TRUE; -If you use the :doc:`form helper <../helpers/form_helper>` the -form_open() function will automatically insert a hidden csrf field in -your forms. +If you use the :doc:`form helper <../helpers/form_helper>`, then +``form_open()`` will automatically insert a hidden csrf field in +your forms. If not, then you can use ``csrf_get_token_name()`` +and ``csrf_get_hash()`` -Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter:: +:: + + $csrf = array( + 'name' => $this->security->csrf_get_token_name(), + 'hash' => $this->security->csrf_get_hash() + ); + + ... + + <input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" /> + +Tokens may be either regenerated on every submission (default) or +kept the same throughout the life of the CSRF cookie. The default +regeneration of tokens provides stricter security, but may result +in usability concerns as other tokens become invalid (back/forward +navigation, multiple tabs/windows, asynchronous actions, etc). You +may alter this behavior by editing the following config parameter + +:: $config['csrf_regeneration'] = TRUE; @@ -95,3 +114,15 @@ by editing the 'csrf_exclude_uris' config parameter:: $config['csrf_exclude_uris'] = array('api/person/add'); +$this->security->get_csrf_token_name() +====================================== + +Returns the CSRF token name, which is set by +``$config['csrf_token_name']``. + +$this->security->get_csrf_hash() +================================ + +Returns the CSRF hash value. Useful in combination with +``get_csrf_token_name()`` for manually building forms or +sending valid AJAX POST requests.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/sessions.rst b/user_guide_src/source/libraries/sessions.rst index e8332ee97..36c7c1d32 100644 --- a/user_guide_src/source/libraries/sessions.rst +++ b/user_guide_src/source/libraries/sessions.rst @@ -1,29 +1,19 @@ -############# -Session Class -############# +############## +Session Driver +############## The Session class permits you maintain a user's "state" and track their -activity while they browse your site. The Session class stores session -information for each user as serialized (and optionally encrypted) data -in a cookie. It can also store the session data in a database table for -added security, as this permits the session ID in the user's cookie to -be matched against the stored session ID. By default only the cookie is -saved. If you choose to use the database option you'll need to create -the session table as indicated below. - -.. note:: The Session class does **not** utilize native PHP sessions. It - generates its own session data, offering more flexibility for - developers. - -.. note:: Even if you are not using encrypted sessions, you must set - an :doc:`encryption key <./encryption>` in your config file which is used - to aid in preventing session data manipulation. +activity while they browse your site. CodeIgniter offers two default +session drivers: the classic `Cookie Driver`_, and the `Native Driver`_, +which supports usage of the native PHP Session mechanism. In addition, +you may create your own `Custom Drivers`_ to store session data however +you wish, while still taking advantage of the features of the Session class. Initializing a Session ====================== Sessions will typically run globally with each page load, so the session -class must either be :doc:`initialized <../general/libraries>` in your +class must either be :doc:`initialized <../general/drivers>` in your :doc:`controller <../general/controllers>` constructors, or it can be :doc:`auto-loaded <../general/autoloader>` by the system. For the most part the session class will run unattended in the background, so simply @@ -31,9 +21,9 @@ initializing the class will cause it to read, create, and update sessions. To initialize the Session class manually in your controller constructor, -use the $this->load->library function:: +use the $this->load->driver function:: - $this->load->library('session'); + $this->load->driver('session'); Once loaded, the Sessions library object will be available using: $this->session @@ -42,11 +32,10 @@ How do Sessions work? ===================== When a page is loaded, the session class will check to see if valid -session data exists in the user's session cookie. If sessions data does -**not** exist (or if it has expired) a new session will be created and -saved in the cookie. If a session does exist, its information will be -updated and the cookie will be updated. With each update, the -session_id will be regenerated. +session data exists in the user's session. If sessions data does **not** +exist (or if it has expired) a new session will be created and saved. +If a session does exist, its information will be updated. With each update, +the session_id will be regenerated. It's important for you to understand that once initialized, the Session class runs automatically. There is nothing you need to do to cause the @@ -79,19 +68,12 @@ prototype:: 'last_activity' => timestamp ) -If you have the encryption option enabled, the serialized array will be -encrypted before being stored in the cookie, making the data highly -secure and impervious to being read or altered by someone. More info -regarding encryption can be :doc:`found here <encryption>`, although -the Session class will take care of initializing and encrypting the data -automatically. - -Note: Session cookies are only updated every five minutes by default to -reduce processor load. If you repeatedly reload a page you'll notice -that the "last activity" time only updates if five minutes or more has -passed since the last time the cookie was written. This time is -configurable by changing the $config['sess_time_to_update'] line in -your system/config/config.php file. +.. note:: Sessions are only updated every five minutes by default to + reduce processor load. If you repeatedly reload a page you'll notice + that the "last activity" time only updates if five minutes or more has + passed since the last time the cookie was written. This time is + configurable by changing the $config['sess_time_to_update'] line in + your system/config/config.php file. Retrieving Session Data ======================= @@ -106,7 +88,7 @@ fetch. For example, to fetch the session ID you will do this:: $session_id = $this->session->userdata('session_id'); -.. note:: The function returns FALSE (boolean) if the item you are +.. note:: The function returns NULL if the item you are trying to access does not exist. Adding Custom Session Data @@ -117,7 +99,7 @@ to it and it will be stored in the user's cookie. Why would you want to do this? Here's one example: Let's say a particular user logs into your site. Once authenticated, you -could add their username and email address to the session cookie, making +could add their username and email address to the session, making that data globally available to you without having to run a database query when you need it. @@ -144,11 +126,11 @@ supports this syntax. $this->session->set_userdata('some_name', 'some_value'); +If you want to verify that a userdata value exists, call has_userdata(). -.. note:: Cookies can only hold 4KB of data, so be careful not to exceed - the capacity. The encryption process in particular produces a longer - data string than the original so keep careful track of how much data you - are storing. +:: + + $this->session->has_userdata('some_name'); Retrieving All Session Data =========================== @@ -195,8 +177,8 @@ available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted"). -Note: Flash variables are prefaced with "flash\_" so avoid this prefix -in your own session names. +.. note:: Flash variables are prefaced with "flash\_" so avoid this prefix + in your own session names. To add flashdata:: @@ -209,7 +191,7 @@ set_userdata(). To read a flashdata variable:: $this->session->flashdata('item'); - + An array of all flashdata can be retrieved as follows:: $this->session->all_flashdata(); @@ -217,14 +199,169 @@ An array of all flashdata can be retrieved as follows:: If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() function. +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')); + +Tempdata +======== + +CodeIgniter also supports "tempdata", or session data with a specific +expiration time. After the value expires, or the session expires or is +deleted, the value is automatically removed. + +To add tempdata:: + + $expire = 300; // Expire in 5 minutes + + $this->session->set_tempdata('item', 'value', $expire); + +You can also pass an array to set_tempdata():: + + $tempdata = array('newuser' => TRUE, 'message' => 'Thanks for joining!'); + + $this->session->set_tempdata($tempdata, '', $expire); + +.. note:: If the expiration is omitted or set to 0, the default expiration of + 5 minutes will be used. + +To read a tempdata variable:: + + $this->session->tempdata('item'); + +If you need to remove a tempdata value before it expires, +use unset_tempdata():: + + $this->session->unset_tempdata('item'); + +Destroying a Session +==================== + +To clear the current session:: + + $this->session->sess_destroy(); + +.. note:: This function should be the last one called, and even flash + variables will no longer be available. If you only want some items + destroyed and not all, use unset_userdata(). + +Session Preferences +=================== + +You'll find the following Session related preferences in your +application/config/config.php file: + +=========================== =============== =========================== ========================================================================== +Preference Default Options Description +=========================== =============== =========================== ========================================================================== +**sess_driver** cookie cookie/native/*custom* The initial session driver to load. +**sess_valid_drivers** cookie, native None Additional valid drivers which may be loaded. +**sess_cookie_name** ci_session None The name you want the session cookie saved as (data for Cookie driver or + session ID for Native driver). +**sess_expiration** 7200 None The number of seconds you would like the session to last. The default + value is 2 hours (7200 seconds). If you would like a non-expiring + session set the value to zero: 0 +**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser + window is closed. +**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data (Cookie driver only). +**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the + table before enabling this option (Cookie driver only). +**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table (Cookie driver only). +**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself + and create a new session id. +**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data. + Note that some ISPs dynamically changes the IP, so if you want a + non-expiring session you will likely set this to FALSE. +**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data. +=========================== =============== =========================== ========================================================================== + +In addition to the values above, the cookie and native drivers apply the +following configuration values shared by the :doc:`Input <input>` and +:doc:`Security <security>` classes: + +=========================== =============== ========================================================================== +Preference Default Description +=========================== =============== ========================================================================== +**cookie_prefix** '' Set a cookie name prefix in order to avoid name collisions +**cookie_domain** '' The domain for which the session is applicable +**cookie_path** / The path to which the session is applicable +=========================== =============== ========================================================================== + +Session Drivers +=============== +By default, the `Cookie Driver`_ is loaded when a session is initialized. +However, any valid driver may be selected with the $config['sess_driver'] +line in your config.php file. + +The session driver library comes with the cookie and native drivers +installed, and `Custom Drivers`_ may also be installed by the user. + +Typically, only one driver will be used at a time, but CodeIgniter does +support loading multiple drivers. If a specific valid driver is called, it +will be automatically loaded. Or, an additional driver may be explicitly +loaded by calling load_driver():: + + $this->session->load_driver('native'); + +The Session library keeps track of the most recently selected driver to call +for driver methods. Normally, session class methods are called directly on +the parent class, as illustrated above. However, any methods called through +a specific driver will select that driver before invoking the parent method. + +So, alternation between multiple drivers can be achieved by specifying which +driver to use for each call:: + + $this->session->native->set_userdata('foo', 'bar'); + + $this->session->cookie->userdata('foo'); + + $this->session->native->unset_userdata('foo'); + +Notice in the previous example that the *native* userdata value 'foo' +would be set to 'bar', which would NOT be returned by the call for +the *cookie* userdata 'foo', nor would the *cookie* value be unset by +the call to unset the *native* 'foo' value. The drivers maintain independent +sets of values, regardless of key names. + +A specific driver may also be explicitly selected for use by pursuant +methods with the select_driver() call:: + + $this->session->select_driver('native'); + + $this->session->userdata('item'); // Uses the native driver + +Cookie Driver +------------- + +The Cookie driver stores session information for each user as serialized +(and optionally encrypted) data in a cookie. It can also store the session +data in a database table for added security, as this permits the session ID +in the user's cookie to be matched against the stored session ID. By default +only the cookie is saved. If you choose to use the database option you'll +need to create the session table as indicated below. + +If you have the encryption option enabled, the serialized array will be +encrypted before being stored in the cookie, making the data highly +secure and impervious to being read or altered by someone. More info +regarding encryption can be :doc:`found here <encryption>`, although +the Session class will take care of initializing and encrypting the data +automatically. + +.. note:: Even if you are not using encrypted sessions, you must set + an :doc:`encryption key <./encryption>` in your config file which is used + to aid in preventing session data manipulation. + +.. note:: Cookies can only hold 4KB of data, so be careful not to exceed + the capacity. The encryption process in particular produces a longer + data string than the original so keep careful track of how much data you + are storing. Saving Session Data to a Database -================================= +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ While the session data array stored in the user's cookie contains a Session ID, unless you store session data in a database there is no way @@ -245,11 +382,11 @@ session class:: CREATE TABLE IF NOT EXISTS `ci_sessions` ( session_id varchar(40) DEFAULT '0' NOT NULL, - ip_address varchar(16) 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), + PRIMARY KEY (session_id, ip_address, user_agent), KEY `last_activity_idx` (`last_activity`) ); @@ -267,44 +404,82 @@ session class:: $config['sess_table_name'] = 'ci_sessions'; -.. note:: The Session class has built-in garbage collection which clears +.. note:: The Cookie driver has built-in garbage collection which clears out expired sessions so you do not need to write your own routine to do it. -Destroying a Session -==================== +Native Driver +------------- -To clear the current session:: +The Native driver relies on native PHP sessions to store data in the +$_SESSION superglobal array. All stored values continue to be available +through $_SESSION, but flash- and temp- data items carry special prefixes. - $this->session->sess_destroy(); +Custom Drivers +-------------- -.. note:: This function should be the last one called, and even flash - variables will no longer be available. If you only want some items - destroyed and not all, use unset_userdata(). +You may also :doc:`create your own <../general/creating_drivers>` custom +session drivers. A session driver basically manages an array of name/value +pairs with some sort of storage mechanism. -Session Preferences -=================== +To make a new driver, extend CI_Session_driver. Overload the initialize() +method and read or create session data. Then implement a save handler to +write changed data to storage (sess_save), a destroy handler to remove +deleted data (sess_destroy), a regenerate handler to make a new session ID +(sess_regenerate), and an access handler to expose the data (get_userdata). +Your initial class might look like:: -You'll find the following Session related preferences in your -application/config/config.php file: + class CI_Session_custom extends CI_Session_driver { + protected function initialize() + { + // Read existing session data or create a new one + } -=========================== =============== =========================== ========================================================================== -Preference Default Options Description -=========================== =============== =========================== ========================================================================== -**sess_cookie_name** ci_session None The name you want the session cookie saved as. -**sess_expiration** 7200 None The number of seconds you would like the session to last. The default - value is 2 hours (7200 seconds). If you would like a non-expiring - session set the value to zero: 0 -**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser - window is closed. -**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data. -**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the - table before enabling this option. -**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table. -**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself - and create a new session id. -**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data. - Note that some ISPs dynamically changes the IP, so if you want a - non-expiring session you will likely set this to FALSE. -**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data. -=========================== =============== =========================== ==========================================================================
\ No newline at end of file + public function sess_save() + { + // Save current data to storage + } + + public function sess_destroy() + { + // Destroy the current session and clean up storage + } + + public function sess_regenerate() + { + // Create new session ID + } + + public function &get_userdata() + { + // Return a reference to your userdata array + } + } + +Notice that get_userdata() returns a reference so the parent library is +accessing the same array the driver object is using. This saves memory +and avoids synchronization issues during usage. + +Put your driver in the libraries/Session/drivers folder anywhere in your +package paths. This includes the application directory, the system directory, +or any path you add with $CI->load->add_package_path(). Your driver must be +named CI_Session_<name>, and your filename must be Session_<name>.php, +preferably also capitalized, such as:: + + CI_Session_foo in libraries/Session/drivers/Session_foo.php + +Then specify the driver by setting 'sess_driver' in your config.php file or as a +parameter when loading the CI_Session object:: + + $config['sess_driver'] = 'foo'; + +OR:: + + $CI->load->driver('session', array('sess_driver' => 'foo')); + +The driver specified by 'sess_driver' is automatically included as a valid +driver. However, if you want to make a custom driver available as an option +without making it the initially loaded driver, set 'sess_valid_drivers' in +your config.php file to an array including your driver name:: + + $config['sess_valid_drivers'] = array('sess_driver'); diff --git a/user_guide_src/source/libraries/trackback.rst b/user_guide_src/source/libraries/trackback.rst index 07b2b2177..f9e0df882 100644 --- a/user_guide_src/source/libraries/trackback.rst +++ b/user_guide_src/source/libraries/trackback.rst @@ -114,7 +114,7 @@ store them. Here is a basic prototype for such a table:: excerpt text NOT NULL, blog_name varchar(100) NOT NULL, tb_date int(10) NOT NULL, - ip_address varchar(16) NOT NULL, + ip_address varchar(45) NOT NULL, PRIMARY KEY `tb_id` (`tb_id`), KEY `entry_id` (`entry_id`) ); diff --git a/user_guide_src/source/libraries/unit_testing.rst b/user_guide_src/source/libraries/unit_testing.rst index 03819b27c..6bd91bf88 100644 --- a/user_guide_src/source/libraries/unit_testing.rst +++ b/user_guide_src/source/libraries/unit_testing.rst @@ -131,7 +131,7 @@ default: - Any notes you entered for the test (notes) You can customize which of these items get displayed by using -$this->unit->set_items(). For example, if you only wanted the test name +$this->unit->set_test_items(). For example, if you only wanted the test name and the result displayed: Customizing displayed tests diff --git a/user_guide_src/source/libraries/uri.rst b/user_guide_src/source/libraries/uri.rst index ee60b77d7..bb959b002 100644 --- a/user_guide_src/source/libraries/uri.rst +++ b/user_guide_src/source/libraries/uri.rst @@ -25,7 +25,7 @@ The segment numbers would be this: #. metro #. crime_is_up -By default the function returns FALSE (boolean) if the segment does not +By default the function returns NULL if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of @@ -146,7 +146,7 @@ full URL:: The function would return this:: - /news/local/345 + news/local/345 $this->uri->ruri_string() ========================== diff --git a/user_guide_src/source/libraries/user_agent.rst b/user_guide_src/source/libraries/user_agent.rst index 855ece29d..97abd2244 100644 --- a/user_guide_src/source/libraries/user_agent.rst +++ b/user_guide_src/source/libraries/user_agent.rst @@ -72,7 +72,7 @@ Returns TRUE/FALSE (boolean) if the user agent is a known web browser. { echo 'You are using Safari.'; } - else if ($this->agent->is_browser()) + elseif ($this->agent->is_browser()) { echo 'You are using a browser.'; } @@ -94,7 +94,7 @@ Returns TRUE/FALSE (boolean) if the user agent is a known mobile device. { $this->load->view('iphone/home'); } - else if ($this->agent->is_mobile()) + elseif ($this->agent->is_mobile()) { $this->load->view('mobile/home'); } diff --git a/user_guide_src/source/libraries/xmlrpc.rst b/user_guide_src/source/libraries/xmlrpc.rst index dfb88114e..b478a2ded 100644 --- a/user_guide_src/source/libraries/xmlrpc.rst +++ b/user_guide_src/source/libraries/xmlrpc.rst @@ -297,7 +297,7 @@ The Client ---------- Using a text editor, create a controller called xmlrpc_client.php. In -it, place this code and save it to your applications/controllers/ +it, place this code and save it to your application/controllers/ folder:: <?php @@ -338,7 +338,7 @@ The Server ---------- Using a text editor, create a controller called xmlrpc_server.php. In -it, place this code and save it to your applications/controllers/ +it, place this code and save it to your application/controllers/ folder:: <?php |