diff options
author | Jonathon Hill <jhill@brandmovers.com> | 2012-11-12 14:51:41 +0100 |
---|---|---|
committer | Jonathon Hill <jhill@brandmovers.com> | 2012-11-12 14:51:41 +0100 |
commit | 3978fc33d82dd7f778d1adbf30744f4dfac41c25 (patch) | |
tree | f32be1ae610f0cfeff65c35abecd14e8ea5cadc6 /user_guide_src | |
parent | 275cf274860c6ed181d50b398efd3a21d7ba9135 (diff) | |
parent | a9ab46d7a031bda304eb9b6658ffaf693b8d9bcb (diff) |
Merge remote-tracking branch 'upstream/develop' into develop
Conflicts:
user_guide_src/source/changelog.rst
Signed-off-by: Jonathon Hill <jhill@brandmovers.com>
Diffstat (limited to 'user_guide_src')
62 files changed, 2739 insertions, 1786 deletions
diff --git a/user_guide_src/source/changelog.rst b/user_guide_src/source/changelog.rst index f45cc5cd7..707d8b3ea 100644 --- a/user_guide_src/source/changelog.rst +++ b/user_guide_src/source/changelog.rst @@ -39,14 +39,16 @@ Release Date: Not Released - Updated support for zip files in mimes.php. - Updated support for csv files in mimes.php. - Added some more doctypes. + - Added Romanian, Greek, Vietnamese and Cyrilic characters in *application/config/foreign_characters.php*. - Added Romanian, Greek and Vietnamese characters in *foreign_characters.php*. - Changed logger to only chmod when file is first created. - Removed previously deprecated SHA1 Library. - - Removed previously deprecated use of ``$autoload['core']`` in application/config/autoload.php. + - Removed previously deprecated use of ``$autoload['core']`` in *application/config/autoload.php*. Only entries in ``$autoload['libraries']`` are auto-loaded now. - Removed previously deprecated EXT constant. - Updated all classes to be written in PHP 5 style, with visibility declarations and no ``var`` usage for properties. - - Moved error templates to "application/views/errors" + - Moved error templates to *application/views/errors/*. + - Moved the Log class to *application/core/* - Global config files are loaded first, then environment ones. Environment config keys overwrite base ones, allowing to only set the keys we want changed per environment. - Changed detection of ``$view_folder`` so that if it's not found in the current path, it will now also be searched for under the application folder. - Path constants BASEPATH, APPPATH and VIEWPATH are now (internally) defined as absolute paths. @@ -54,6 +56,7 @@ Release Date: Not Released - Changed environment defaults to report all errors in *development* and only fatal ones in *testing*, *production* but only display them in *development*. - Updated *ip_address* database field lengths from 16 to 45 for supporting IPv6 address on :doc:`Trackback Library <libraries/trackback>` and :doc:`Captcha Helper <helpers/captcha_helper>`. - Removed *cheatsheets* and *quick_reference* PDFs from the documentation. + - Added availability checks where usage of dangerous functions like ``eval()`` and ``exec()`` is required. - Helpers @@ -65,35 +68,63 @@ Release Date: Not Released - Added function ``date_range()`` that generates a list of dates between a specified period. - ``create_captcha()`` accepts additional colors parameter, allowing for color customization. - :doc:`URL Helper <helpers/url_helper>` changes include: - - ``url_title()`` will now trim extra dashes from beginning and end. - - ``anchor_popup()`` will now fill the *href* attribute with the URL and its JS code will return FALSE instead. - - Added JS window name support to ``anchor_popup()`` function. - - Added support (auto-detection) for HTTP/1.1 response code 303 in ``redirect()``. - - "auto" method in ``redirect()`` now chooses the "refresh" method only on IIS servers, instead of all servers on Windows. + - Deprecated *separator* options **dash** and **underscore** for function :php:func:`url_title()` (they are only aliases for '-' and '_' respectively). + - :php:func:`url_title()` will now trim extra dashes from beginning and end. + - :php:func:`anchor_popup()` will now fill the *href* attribute with the URL and its JS code will return FALSE instead. + - Added JS window name support to the :php:func:`anchor_popup()` function. + - Added support (auto-detection) for HTTP/1.1 response code 303 in :php:func:`redirect()`. + - Changed :php:func:`redirect()` to only choose the **refresh** method only on IIS servers, instead of all servers on Windows (when **auto** is used). - Added XHTML Basic 1.1 doctype to :doc:`HTML Helper <helpers/html_helper>`. - - Changed ``humanize()`` to include a second param for the separator. - - Refactored ``plural()`` and ``singular()`` to avoid double pluralization and support more words. + - :doc:`Inflector Helper <helpers/inflector_helper>` changes include: + - Changed :php:func:`humanize()` to allow passing an input separator as its second parameter. + - Refactored :php:func:`plural()` and :php:func:`singular()` to avoid double pluralization and support more words. - Added an optional third parameter to ``force_download()`` that enables/disables sending the actual file MIME type in the Content-Type header (disabled by default). - Added a work-around in ``force_download()`` for a bug Android <= 2.1, where the filename extension needs to be in uppercase. - :doc:`Form Helper <helpers/form_helper>` changes include: - - ``form_dropdown()`` will now also take an array for unity with other form helpers. - - ``form_prep()`` is now **DEPRECATED** and only acts as an alias for :doc:`common function <general/common_functions>` ``html_escape()``. - - ``do_hash()`` now uses PHP's native ``hash()`` function (supporting more algorithms) and is deprecated. + - :php:func:`form_dropdown()` will now also take an array for unity with other form helpers. + - :php:func:`form_prep()`'s second argument now only accepts a boolean value, which determines whether the value is escaped for a <textarea> or a regular <input> element. + - :doc:`Security Helper <helpers/security_helper>` changes include: + - :php:func:`do_hash()` now uses PHP's native ``hash()`` function (supporting more algorithms) and is deprecated. + - :php:func:`strip_image_tags()` is now an alias for the same method in the :doc:`Security Library <libraries/security>`. - Removed previously deprecated helper function ``js_insert_smiley()`` from :doc:`Smiley Helper <helpers/smiley_helper>`. - :doc:`File Helper <helpers/file_helper>` changes include: - - ``set_realpath()`` can now also handle file paths as opposed to just directories. - - Added an optional paramater to ``delete_files()`` to enable it to skip deleting files such as .htaccess and index.html. - - ``read_file()`` is now a deprecated alias of ``file_get_contents()``. - - :doc:`Security Helper <helpers/security_helper>` function ``strip_image_tags()`` is now an alias for the same method in the :doc:`Security Library <libraries/security>`. - - Deprecated :doc:`String Helper <helpers/string_helper>` function ``repeater()`` - it's just an alias for PHP's native ``str_repeat()``. + - :php:func:`set_realpath()` can now also handle file paths as opposed to just directories. + - Added an optional paramater to :php:func:`delete_files()` to enable it to skip deleting files such as *.htaccess* and *index.html*. + - Deprecated function ``read_file()`` - it's just an alias for PHP's native ``file_get_contents()``. + - :doc:`String Helper <helpers/string_helper>` changes include: + - Deprecated function ``repeater()`` - it's just an alias for PHP's native ``str_repeat()``. + - Deprecated function ``trim_slashes()`` - it's just an alias for PHP's native ``trim()`` (with a slash as its second argument). + - Deprecated randomization type options **unique** and **encrypt** for funcion :php:func:`random_string()` (they are only aliases for **md5** and **sha1** respectively). + - :doc:`Directory Helper <helpers/directory_helper>` ``directory_map()`` will now append DIRECTORY_SEPARATOR to directory names in the returned array. + - Deprecated the :doc:`Email Helper <helpers/email_helper>` as its ``valid_email()``, ``send_email()`` functions are now only aliases for PHP native functions ``filter_var()`` and ``mail()`` respectively. - Database + - Added **dsn** configuration setting for drivers that support DSN strings (PDO, PostgreSQL, Oracle, ODBC, CUBRID). + - Added **schema** configuration setting (defaults to *public*) for drivers that might need it (currently used by PostgreSQL and ODBC). + - Added subdrivers support (currently only used by PDO). + - Added an optional database name parameter to ``db_select()``. + - Added a constructor to the ``DB_result`` class and moved all driver-specific properties and logic out of the base ``DB_driver`` class to allow better abstraction. + - Removed ``protect_identifiers()`` and renamed internal method ``_protect_identifiers()`` to it instead - it was just an alias. + - Renamed internal method ``_escape_identifiers()`` to ``escape_identifiers()``. + - Updated ``escape_identifiers()`` to accept an array of fields as well as strings. + - MySQL and MySQLi drivers now require at least MySQL version 5.1. + - ``db_set_charset()`` now only requires one parameter (collation was only needed due to legacy support for MySQL versions prior to 5.1). + - Replaced the ``_error_message()`` and ``_error_number()`` methods with ``error()``, which returns an array containing the last database error code and message. + - Improved ``version()`` implementation so that drivers that have a native function to get the version number don't have to be defined in the core ``DB_driver`` class. + - Added ``unbuffered_row()`` method for getting a row without prefetching whole result (consume less memory). + - Added capability for packages to hold *database.php* config files. + - Added MySQL client compression support. + - Added encrypted connections support (for *mysql*, *sqlsrv* and PDO with *sqlsrv*). + - Removed :doc:`Loader Class <libraries/loader>` from Database error tracing to better find the likely culprit. + - Added support for SQLite3 database driver. + - Added Interbase/Firebird database support via the *ibase* driver. + - Added ODBC support for ``create_database()``, ``drop_database()`` and ``drop_table()`` in :doc:`Database Forge <database/forge>`. - :doc:`Query Builder <database/query_builder>` changes include: - Renamed the Active Record class to Query Builder to remove confusion with the Active Record design pattern. - Added the ability to insert objects with ``insert_batch()``. - Added new methods that return the SQL string of queries without executing them: ``get_compiled_select()``, ``get_compiled_insert()``, ``get_compiled_update()``, ``get_compiled_delete()``. - - Added an optional parameter that allows to disable escaping (useful for custom fields) for methods ``join()``, ``order_by()``, ``where_in()``, ``or_where_in()``, ``where_not_in()``, ``or_where_not_in()``. + - Added an optional parameter that allows to disable escaping (useful for custom fields) for methods ``join()``, ``order_by()``, ``where_in()``, ``or_where_in()``, ``where_not_in()``, ``or_where_not_in()``, ``insert()``, ``insert_batch()``. - Added support for ``join()`` with multiple conditions. - Added support for *USING* in ``join()``. - Changed ``limit()`` to ignore NULL values instead of always casting to integer. @@ -104,13 +135,10 @@ Release Date: Not Released - Server version checking is now done via ``mysqli::$server_info`` instead of running an SQL query. - Added persistent connections support for PHP >= 5.3. - Added support for ``backup()`` in :doc:`Database Utilities <database/utilities>`. - - Added **dsn** configuration setting for drivers that support DSN strings (PDO, PostgreSQL, Oracle, ODBC, CUBRID). - - Added **schema** configuration setting (defaults to *public*) for drivers that might need it (currently used by PostgreSQL and ODBC). - - Improved PDO database support. - - Added Interbase/Firebird database support via the *ibase* driver. - - Added an optional database name parameter to ``db_select()``. - - Replaced the ``_error_message()`` and ``_error_number()`` methods with ``error()``, which returns an array containing the last database error code and message. - - Improved ``version()`` implementation so that drivers that have a native function to get the version number don't have to be defined in the core ``DB_driver`` class. + - Improved support of the PDO driver, including: + - Added support for ``create_database()``, ``drop_database()`` and ``drop_table()`` in :doc:`Database Forge <database/forge>`. + - Added support for ``list_fields()`` in :doc:`Database Results <database/results>`. + - Subdrivers are now isolated from each other instead of being in one large class. - Improved support of the PostgreSQL driver, including: - ``pg_version()`` is now used to get the database version number, when possible. - Added ``db_set_charset()`` support. @@ -119,13 +147,6 @@ Release Date: Not Released - Added ``update_batch()`` support. - Removed ``limit()`` and ``order_by()`` support for *UPDATE* and *DELETE* queries as PostgreSQL does not support those features. - Added a work-around for dead persistent connections to be re-created after a database restart. - - Added a constructor to the ``DB_result`` class and moved all driver-specific properties and logic out of the base ``DB_driver`` class to allow better abstraction. - - Removed ``protect_identifiers()`` and renamed internal method ``_protect_identifiers()`` to it instead - it was just an alias. - - Renamed internal method ``_escape_identifiers()`` to ``escape_identifiers()``. - - Updated ``escape_identifiers()`` to accept an array of fields as well as strings. - - MySQL and MySQLi drivers now require at least MySQL version 5.1. - - ``db_set_charset()`` now only requires one parameter (collation was only needed due to legacy support for MySQL versions prior to 5.1). - - Added support for SQLite3 database driver. - Improved support of the CUBRID driver, including: - Added DSN string support. - Added persistent connections support. @@ -145,15 +166,16 @@ Release Date: Not Released - Improved support of the SQLite driver, including: - Added support for ``replace()`` in :doc:`Query Builder <database/query_builder>`. - Added support for ``drop_table()`` in :doc:`Database Forge <database/forge>`. - - Added ODBC support for ``create_database()``, ``drop_database()`` and ``drop_table()`` in :doc:`Database Forge <database/forge>`. - - Added PDO support for ``create_database()``, ``drop_database()`` and ``drop_table()`` in :doc:`Database Forge <database/forge>`. - - Added ``unbuffered_row()`` method for getting a row without prefetching whole result (consume less memory). - - Added PDO support for ``list_fields()`` in :doc:`Database Results <database/results>`. - - Added capability for packages to hold *database.php* config files - - Added subdrivers support (currently only used by PDO). - - Added MySQL client compression support. - - Added encrypted connections support (for *mysql*, *sqlsrv* and PDO with *sqlsrv*). - - Removed :doc:`Loader Class <libraries/loader>` from Database error tracing to better find the likely culprit. + - :doc:`Database Forge <database/forge>` changes include: + - Added an optional second parameter to ``drop_table()`` that allows adding the **IF EXISTS** condition, which is no longer the default. + - Added support for passing a custom database object to the loader. + - Deprecated ``add_column()``'s third method. *AFTER* clause should now be added to the field definition array instead. + - Added support for usage of the *FIRST* clause in ``add_column()`` for MySQL and CUBRID. + - Overall improved support for all of the drivers. + - :doc:`Database Utility <database/utilities>` chages include: + - Added support for passing a custom database object to the loader. + - Modified the class to no longer extend :doc:`Database Forge <database/forge>`, which has been a deprecated behavior for awhile. + - Overall improved support for all of the drivers. - Libraries @@ -182,7 +204,7 @@ Release Date: Not Released - Added method ``remove()`` to remove a cart item, updating with quantity of 0 seemed like a hack but has remained to retain compatibility. - Added method ``get_item()`` to enable retrieving data for a single cart item. - :doc:`Image Manipulation library <libraries/image_lib>` changes include: - - The initialize() method now only sets existing class properties. + - The ``initialize()`` method now only sets existing class properties. - Added support for 3-length hex color values for *wm_font_color* and *wm_shadow_color* properties, as well as validation for them. - Class properties *wm_font_color*, *wm_shadow_color* and *wm_use_drop_shadow* are now protected, to avoid breaking the ``text_watermark()`` method if they are set manually after initialization. - If property *maintain_ratio* is set to TRUE, ``image_reproportion()`` now doesn't need both width and height to be specified. @@ -227,13 +249,20 @@ Release Date: Not Released - Added support for hashing algorithms other than SHA1 and MD5. - Removed previously deprecated ``sha1()`` method. - Changed :doc:`Language Library <libraries/language>` method ``load()`` to filter the language name with ``ctype_digit()``. + - :doc:`Profiler Library <general/profiling>` now also displays database object names. - :doc:`Migration Library <libraries/migration>` changes include: - Added support for timestamp-based migrations (enabled by default) - Added ``$config['migration_style']`` to allow switching between sequential migrations and timestamp migrations - Core - - Changed private methods in the :doc:`URI Library <libraries/uri>` to protected so MY_URI can override them. + - :doc:`URI Library <libraries/uri>` changes include: + - Changed private methods to protected so that MY_URI can override them. + - Renamed internal method ``_parse_cli_args()`` to ``_parse_argv()``. + - Renamed internal method ``_detect_uri()`` to ``_parse_request_uri()``. + - Changed ``_parse_request_uri()`` to accept absolute URIs for compatibility with HTTP/1.1 as per `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`. + - Added protected method ``_parse_query_string()`` to URI paths in the the **QUERY_STRING** value, like ``_parse_request_uri()`` does. + - Changed ``_fetch_uri_string()`` to try the **PATH_INFO** variable first when auto-detecting. - Removed ``CI_CORE`` boolean constant from *CodeIgniter.php* (no longer Reactor and Core versions). - :doc:`Loader Library <libraries/loader>` changes include: - Added method ``get_vars()`` to the Loader to retrieve all variables loaded with ``$this->load->vars()``. @@ -245,15 +274,17 @@ Release Date: Not Released - :doc:`Input Library <libraries/input>` changes include: - Added ``method()`` to retrieve ``$_SERVER['REQUEST_METHOD']``. - Added support for arrays and network addresses (e.g. 192.168.1.1/24) for use with the *proxy_ips* setting. + - Added method ``input_stream()`` to aid in using **php://input** stream data such as one passed via PUT, DELETE and PATCH requests. - Changed method ``valid_ip()`` to use PHP's native ``filter_var()`` function. - Changed internal method ``_sanitize_globals()`` to skip enforcing reversal of *register_globals* in PHP 5.4+, where this functionality no longer exists. - Changed methods ``get()``, ``post()``, ``get_post()``, ``cookie()``, ``server()``, ``user_agent()`` to return NULL instead of FALSE when no value is found. - :doc:`Common functions <general/common_functions>` changes include: - - Added function ``get_mimes()`` to return the *config/mimes.php* array. - - Added support for HTTP code 303 ("See Other") in ``set_status_header()``. - - Removed redundant conditional to determine HTTP server protocol in ``set_status_header()``. + - Added function :php:func:`get_mimes()` to return the *application/config/mimes.php* array. + - Added support for HTTP code 303 ("See Other") in :php:func:`set_status_header()`. + - Removed redundant conditional to determine HTTP server protocol in :php:func:`set_status_header()`. - Changed ``_exception_handler()`` to respect php.ini *display_errors* setting. - - Added function ``is_https()`` to check if a secure connection is used. + - Added function :php:func:`is_https()` to check if a secure connection is used. + - Added function :php:func:`function_usable()` to check if a function exists and is not disabled by `Suhosin <http://www.hardened-php.net/suhosin/>`. - Added support for HTTP-Only cookies with new config option *cookie_httponly* (default FALSE). - Renamed method ``_call_hook()`` to ``call_hook()`` in the :doc:`Hooks Library <general/hooks>`. - :doc:`Output Library <libraries/output>` changes include: @@ -267,6 +298,9 @@ Release Date: Not Released - Added method ``strip_image_tags()``. - Added ``$config['csrf_regeneration']``, which makes token regeneration optional. - Added ``$config['csrf_exclude_uris']``, which allows you list URIs which will not have the CSRF validation methods run. + - :doc:`URI Routing <general/routing>` changes include: + - Added possibility to route requests using callbacks. + - Added possibility to use dashes in the controller and method URI segments (translated to underscores). Bug fixes for 3.0 ------------------ @@ -403,7 +437,14 @@ Bug fixes for 3.0 - Fixed a bug (#142) - :doc:`Form Helper <helpers/form_helper>` function ``form_dropdown()`` didn't escape HTML entities in option values. - Fixed a bug (#50) - :doc:`Session Library <libraries/sessions>` unnecessarily stripped slashed from serialized data, making it impossible to read objects in a namespace. - Fixed a bug (#658) - :doc:`Routing <general/routing>` wildcard **:any** didn't work as advertised and matched multiple URI segments instead of all characters within a single segment. -- Fixed a bug (#1938) - :doc:`Email <libraries/email>` where the email library removed multiple spaces inside a pre-formatted plain text message. +- Fixed a bug (#1938) - :doc:`Email Library <libraries/email>` removed multiple spaces inside a pre-formatted plain text message. +- Fixed a bug (#388, #705) - :doc:`URI Library <libraries/uri>` didn't apply URL-decoding to URI segments that it got from **REQUEST_URI** and/or **QUERY_STRING**. +- Fixed a bug (#122) - :doc:`URI Library <libraries/uri>` method ``ruri_string()`` didn't include a directory if one is used. +- Fixed a bug - :doc:`Routing Library <general/routing>` didn't properly handle *default_controller* in a subdirectory when a method is also specified. +- Fixed a bug (#953) - :doc:`post_controller_constructor hook <general/hooks>` wasn't called with a *404_override*. +- Fixed a bug (#1220) - :doc:`Profiler Library <general/profiling>` didn't display information for database objects that are instantiated inside models. +- Fixed a bug (#1978) - :doc:`Directory Helper <helpers/directory_helper>` function :php:func:`directory_map()`'s return array didn't make a distinction between directories and file indexes when a directory with a numeric name is present. +- Fixed a bug (#777) - :doc:`Loader Library <libraries/loader>` didn't look for helper extensions in added package paths. Version 2.1.3 ============= diff --git a/user_guide_src/source/contributing/index.rst b/user_guide_src/source/contributing/index.rst index 2ede0e6e5..0771a4192 100644 --- a/user_guide_src/source/contributing/index.rst +++ b/user_guide_src/source/contributing/index.rst @@ -102,4 +102,4 @@ it. By signing your work in this manner, you certify to a "Developer's Certificate or Origin". The current version of this certificate is in the :doc:`/DCO` file -in the root of this documentation. +in the root of this documentation.
\ No newline at end of file diff --git a/user_guide_src/source/database/forge.rst b/user_guide_src/source/database/forge.rst index bf17e2918..ca904ed00 100644 --- a/user_guide_src/source/database/forge.rst +++ b/user_guide_src/source/database/forge.rst @@ -2,7 +2,7 @@ Database Forge Class #################### -The Database Forge Class contains functions that help you manage your +The Database Forge Class contains methods that help you manage your database. .. contents:: Table of Contents @@ -18,13 +18,25 @@ Load the Forge Class as follows:: $this->load->dbforge() -Once initialized you will access the functions using the $this->dbforge +You can also pass another database object to the DB Forge loader, in case +the database you want to manage isn't the default one:: + + $this->myforge = $this->load->dbforge($this->other_db, TRUE); + +In the above example, we're passing a custom database object as the first +parameter and then tell it to return the dbforge object, instead of +assigning it directly to ``$this->dbforge``. + +.. note:: Both of the parameters can be used individually, just pass an empty + value as the first one if you wish to skip it. + +Once initialized you will access the methods using the ``$this->dbforge`` object:: - $this->dbforge->some_function() + $this->dbforge->some_method(); $this->dbforge->create_database('db_name') -============================================ +========================================== Permits you to create the database specified in the first parameter. Returns TRUE/FALSE based on success or failure:: @@ -108,13 +120,13 @@ Additionally, the following key/values can be used: After the fields have been defined, they can be added using -$this->dbforge->add_field($fields); followed by a call to the -create_table() function. +``$this->dbforge->add_field($fields);`` followed by a call to the +``create_table()`` method. $this->dbforge->add_field() ----------------------------- +--------------------------- -The add fields function will accept the above array. +The add fields method will accept the above array. Passing strings as fields ------------------------- @@ -193,13 +205,15 @@ into the definition Dropping a table ================ -Executes a DROP TABLE sql +Execute a DROP TABLE statement and optionally add an IF EXISTS clause. :: + // Produces: DROP TABLE table_name $this->dbforge->drop_table('table_name'); - // gives DROP TABLE IF EXISTS table_name + // Produces: DROP TABLE IF EXISTS table_name + $this->dbforge->drop_table('table_name'); Renaming a table ================ @@ -217,9 +231,9 @@ Modifying Tables **************** $this->dbforge->add_column() -============================= +============================ -The add_column() function is used to modify an existing table. It +The ``add_column()`` method is used to modify an existing table. It accepts the same field array as above, and can be used for an unlimited number of additional fields. @@ -229,18 +243,25 @@ number of additional fields. 'preferences' => array('type' => 'TEXT') ); $this->dbforge->add_column('table_name', $fields); - // gives ALTER TABLE table_name ADD preferences TEXT + // Executes: ALTER TABLE table_name ADD preferences TEXT -An optional third parameter can be used to specify which existing column -to add the new column after. +If you are using MySQL or CUBIRD, then you can take advantage of their +AFTER and FIRST clauses to position the new column. -:: +Examples:: - $this->dbforge->add_column('table_name', $fields, 'after_field'); + // Will place the new column after the `another_field` column: + $fields = array( + 'preferences' => array('type' => 'TEXT', 'after' => 'another_field') + ); + // Will place the new column at the start of the table definition: + $fields = array( + 'preferences' => array('type' => 'TEXT', 'first' => TRUE) + ); $this->dbforge->drop_column() -============================== +============================= Used to remove a column from a table. @@ -250,9 +271,9 @@ Used to remove a column from a table. $this->dbforge->modify_column() -================================ +=============================== -The usage of this function is identical to add_column(), except it +The usage of this method is identical to ``add_column()``, except it alters an existing column rather than adding a new one. In order to change the name you can add a "name" key into the field defining array. diff --git a/user_guide_src/source/database/utilities.rst b/user_guide_src/source/database/utilities.rst index 4e83929b2..06ecb2da1 100644 --- a/user_guide_src/source/database/utilities.rst +++ b/user_guide_src/source/database/utilities.rst @@ -2,7 +2,7 @@ Database Utility Class ###################### -The Database Utility Class contains functions that help you manage your +The Database Utility Class contains methods that help you manage your database. .. contents:: Table of Contents @@ -22,12 +22,24 @@ Load the Utility Class as follows:: $this->load->dbutil() -Once initialized you will access the functions using the $this->dbutil +You can also pass another database object to the DB Utility loader, in case +the database you want to manage isn't the default one:: + + $this->myutil = $this->load->dbutil($this->other_db, TRUE); + +In the above example, we're passing a custom database object as the first +parameter and then tell it to return the dbutil object, instead of +assigning it directly to ``$this->dbutil``. + +.. note:: Both of the parameters can be used individually, just pass an empty + value as the first one if you wish to skip it. + +Once initialized you will access the methods using the ``$this->dbutil`` object:: - $this->dbutil->some_function() + $this->dbutil->some_method() -$this->dbutil->list_databases() +$this->dbutil->list_databases(); ================================ Returns an array of database names:: @@ -40,7 +52,7 @@ Returns an array of database names:: } $this->dbutil->database_exists(); -================================== +================================= Sometimes it's helpful to know whether a particular database exists. Returns a boolean TRUE/FALSE. Usage example:: @@ -50,13 +62,11 @@ Returns a boolean TRUE/FALSE. Usage example:: // some code... } -Note: Replace *database_name* with the name of the table you are -looking for. This function is case sensitive. +.. note:: Replace *database_name* with the name of the table you are + looking for. This method is case sensitive. $this->dbutil->optimize_table('table_name'); -============================================== - -.. note:: This features is only available for MySQL/MySQLi databases. +============================================ Permits you to optimize a table using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:: @@ -66,12 +76,11 @@ first parameter. Returns TRUE/FALSE based on success or failure:: echo 'Success!'; } -.. note:: Not all database platforms support table optimization. +.. note:: Not all database platforms support table optimization. It is + mostly for use with MySQL. $this->dbutil->repair_table('table_name'); -============================================ - -.. note:: This features is only available for MySQL/MySQLi databases. +========================================== Permits you to repair a table using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:: @@ -86,8 +95,6 @@ first parameter. Returns TRUE/FALSE based on success or failure:: $this->dbutil->optimize_database(); ==================================== -.. note:: This features is only available for MySQL/MySQLi databases. - Permits you to optimize the database your DB class is currently connected to. Returns an array containing the DB status messages or FALSE on failure. @@ -101,13 +108,14 @@ FALSE on failure. print_r($result); } -.. note:: Not all database platforms support table optimization. +.. note:: Not all database platforms support table optimization. It + it is mostly for use with MySQL. -$this->dbutil->csv_from_result($db_result) -============================================= +$this->dbutil->csv_from_result($db_result); +=========================================== Permits you to generate a CSV file from a query result. The first -parameter of the function must contain the result object from your +parameter of the method must contain the result object from your query. Example:: $this->load->dbutil(); @@ -127,12 +135,12 @@ is used as the enclosure. Example:: echo $this->dbutil->csv_from_result($query, $delimiter, $newline, $enclosure); -.. important:: This function will NOT write the CSV file for you. It +.. important:: This method will NOT write the CSV file for you. It simply creates the CSV layout. If you need to write the file use the :doc:`File Helper <../helpers/file_helper>`. -$this->dbutil->xml_from_result($db_result) -============================================= +$this->dbutil->xml_from_result($db_result); +=========================================== Permits you to generate an XML file from a query result. The first parameter expects a query result object, the second may contain an @@ -151,17 +159,17 @@ optional array of config parameters. Example:: echo $this->dbutil->xml_from_result($query, $config); -.. important:: This function will NOT write the XML file for you. It +.. important:: This method will NOT write the XML file for you. It simply creates the XML layout. If you need to write the file use the :doc:`File Helper <../helpers/file_helper>`. -$this->dbutil->backup() -======================= +$this->dbutil->backup(); +======================== Permits you to backup your full database or individual tables. The backup data can be compressed in either Zip or Gzip format. -.. note:: This features is only available for MySQL and Interbase/Firebird databases. +.. note:: This feature is only available for MySQL and Interbase/Firebird databases. .. note:: For Interbase/Firebird databases, the backup file name is the only parameter. @@ -196,16 +204,16 @@ Setting Backup Preferences -------------------------- Backup preferences are set by submitting an array of values to the first -parameter of the backup function. Example:: +parameter of the ``backup()`` method. Example:: $prefs = array( - 'tables' => array('table1', 'table2'), // Array of tables to backup. - 'ignore' => array(), // List of tables to omit from the backup - 'format' => 'txt', // gzip, zip, txt - 'filename' => 'mybackup.sql', // File name - NEEDED ONLY WITH ZIP FILES - 'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file - 'add_insert' => TRUE, // Whether to add INSERT data to backup file - 'newline' => "\n" // Newline character used in backup file + 'tables' => array('table1', 'table2'), // Array of tables to backup. + 'ignore' => array(), // List of tables to omit from the backup + 'format' => 'txt', // gzip, zip, txt + 'filename' => 'mybackup.sql', // File name - NEEDED ONLY WITH ZIP FILES + 'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file + 'add_insert' => TRUE, // Whether to add INSERT data to backup file + 'newline' => "\n" // Newline character used in backup file ); $this->dbutil->backup($prefs); diff --git a/user_guide_src/source/general/alternative_php.rst b/user_guide_src/source/general/alternative_php.rst index 4dc857a50..418d2e6eb 100644 --- a/user_guide_src/source/general/alternative_php.rst +++ b/user_guide_src/source/general/alternative_php.rst @@ -17,12 +17,12 @@ Automatic Short Tag Support work on your server it might be that "short tags" are disabled in your PHP ini file. CodeIgniter will optionally rewrite short tags on-the-fly, allowing you to use that syntax even if your server doesn't support it. - This feature can be enabled in your config/config.php file. + This feature can be enabled in your *config/config.php* file. Please note that if you do use this feature, if PHP errors are encountered in your **view files**, the error message and line number will not be accurately shown. Instead, all errors will be shown as -eval() errors. +``eval()`` errors. Alternative Echos ================= @@ -39,13 +39,13 @@ Alternative Control Structures ============================== Controls structures, like if, for, foreach, and while can be written in -a simplified format as well. Here is an example using foreach:: +a simplified format as well. Here is an example using ``foreach``:: <ul> <?php foreach ($todo as $item): ?> - <li><?=$item?></li> + <li><?=$item?></li> <?php endforeach; ?> @@ -60,17 +60,16 @@ Also notice that instead of using a semicolon after each structure Here is another example, using ``if``/``elseif``/``else``. Notice the colons:: - <?php if ($username == 'sally'): ?> + <?php if ($username === 'sally'): ?> - <h3>Hi Sally</h3> + <h3>Hi Sally</h3> - <?php elseif ($username == 'joe'): ?> + <?php elseif ($username === 'joe'): ?> - <h3>Hi Joe</h3> + <h3>Hi Joe</h3> <?php else: ?> - <h3>Hi unknown user</h3> - - <?php endif; ?> + <h3>Hi unknown user</h3> + <?php endif; ?>
\ No newline at end of file diff --git a/user_guide_src/source/general/ancillary_classes.rst b/user_guide_src/source/general/ancillary_classes.rst index f7c87011b..a4befc7b3 100644 --- a/user_guide_src/source/general/ancillary_classes.rst +++ b/user_guide_src/source/general/ancillary_classes.rst @@ -7,31 +7,35 @@ controllers but have the ability to utilize all of CodeIgniter's resources. This is easily possible as you'll see. get_instance() -=============== +============== -**Any class that you instantiate within your controller functions can +.. php:function:: get_instance() + + :returns: object of class CI_Controller + +**Any class that you instantiate within your controller methods can access CodeIgniter's native resources** simply by using the -get_instance() function. This function returns the main CodeIgniter -object. +``get_instance()`` function. This function returns the main +CodeIgniter object. -Normally, to call any of the available CodeIgniter functions requires -you to use the $this construct:: +Normally, to call any of the available CodeIgniter methods requires +you to use the ``$this`` construct:: $this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url'); // etc. -$this, however, only works within your controllers, your models, or your -views. If you would like to use CodeIgniter's classes from within your -own custom classes you can do so as follows: +``$this``, however, only works within your controllers, your models, +or your views. If you would like to use CodeIgniter's classes from +within your own custom classes you can do so as follows: First, assign the CodeIgniter object to a variable:: $CI =& get_instance(); Once you've assigned the object to a variable, you'll use that variable -*instead* of $this:: +*instead* of ``$this``:: $CI =& get_instance(); @@ -40,10 +44,45 @@ Once you've assigned the object to a variable, you'll use that variable $CI->config->item('base_url'); // etc. -.. note:: You'll notice that the above get_instance() function is being +.. note:: You'll notice that the above get_instance() ``function`` is being passed by reference:: $CI =& get_instance(); This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it. + +Furthermore, if you'll be using ``get_intance()`` inside anoter class, +then it would be better if you assign it to a property. This way, you +won't need to call ``get_instance()`` in every single method. + +Example:: + +class Example { + + protected $CI; + + // We'll use a constructor, as you can't directly call a function + // from a property definition. + public function __construct() + { + // Assign the CodeIgniter super-object + $this->CI =& get_instance(); + } + + public function foo() + { + $this->CI->load->helper('url'); + redirect(); + } + + public function bar() + { + $this->CI->config_item('base_url'); + } + +} + +In the above example, both methods ``foo()`` and ``bar()`` will work +after you instantiate the Example class, without the need to call +``get_instance()`` in each of them.
\ No newline at end of file diff --git a/user_guide_src/source/general/autoloader.rst b/user_guide_src/source/general/autoloader.rst index 8ecc13cb6..e5cec723b 100644 --- a/user_guide_src/source/general/autoloader.rst +++ b/user_guide_src/source/general/autoloader.rst @@ -9,15 +9,15 @@ application you should consider auto-loading them for convenience. The following items can be loaded automatically: -- Classes found in the "libraries" folder -- Helper files found in the "helpers" folder -- Custom config files found in the "config" folder -- Language files found in the "system/language" folder -- Models found in the "models" folder +- Classes found in the *libraries/* directory +- Helper files found in the *helpers/* directory +- Custom config files found in the *config/* directory +- Language files found in the *system/language/* directory +- Models found in the *models/* folder -To autoload resources, open the application/config/autoload.php file and -add the item you want loaded to the autoload array. You'll find -instructions in that file corresponding to each type of item. +To autoload resources, open the *application/config/autoload.php* +file and add the item you want loaded to the autoload array. You'll +find instructions in that file corresponding to each type of item. .. note:: Do not include the file extension (.php) when adding items to - the autoload array. + the autoload array.
\ No newline at end of file diff --git a/user_guide_src/source/general/caching.rst b/user_guide_src/source/general/caching.rst index bf6ed50f6..c40f652ac 100644 --- a/user_guide_src/source/general/caching.rst +++ b/user_guide_src/source/general/caching.rst @@ -23,36 +23,38 @@ will be retrieved and sent to the requesting user's browser. If it has expired, it will be deleted and refreshed before being sent to the browser. -Note: The Benchmark tag is not cached so you can still view your page -load speed when caching is enabled. +.. note: The Benchmark tag is not cached so you can still view your page + load speed when caching is enabled. Enabling Caching ================ To enable caching, put the following tag in any of your controller -functions:: +methods:: - $this->output->cache(n); + $this->output->cache($n); -Where n is the number of **minutes** you wish the page to remain cached -between refreshes. +Where ``$n`` is the number of **minutes** you wish the page to remain +cached between refreshes. -The above tag can go anywhere within a function. It is not affected by +The above tag can go anywhere within a method. It is not affected by the order that it appears, so place it wherever it seems most logical to you. Once the tag is in place, your pages will begin being cached. .. important:: Because of the way CodeIgniter stores content for output, - caching will only work if you are generating display for your controller - with a :doc:`view <./views>`. + caching will only work if you are generating display for your + controller with a :doc:`view <./views>`. .. note:: Before the cache files can be written you must set the file - permissions on your application/cache folder such that it is writable. + permissions on your *application/cache/* directory such that + it is writable. Deleting Caches =============== If you no longer wish to cache a file you can remove the caching tag and -it will no longer be refreshed when it expires. Note: Removing the tag -will not delete the cache immediately. It will have to expire normally. -If you need to remove it earlier you will need to manually delete it -from your cache folder. +it will no longer be refreshed when it expires. + +.. note:: Removing the tag will not delete the cache immediately. It will + have to expire normally. If you need to remove it earlier you + will need to manually delete it from your cache directory.
\ No newline at end of file diff --git a/user_guide_src/source/general/cli.rst b/user_guide_src/source/general/cli.rst index 649d5d548..998d2a907 100644 --- a/user_guide_src/source/general/cli.rst +++ b/user_guide_src/source/general/cli.rst @@ -21,7 +21,7 @@ Why run via the command-line? There are many reasons for running CodeIgniter from the command-line, but they are not always obvious. -- Run your cron-jobs without needing to use wget or curl +- Run your cron-jobs without needing to use *wget* or *curl* - Make your cron-jobs inaccessible from being loaded in the URL by checking for ``$this->input->is_cli_request()`` - Make interactive "tasks" that can do things like set permissions, @@ -44,9 +44,8 @@ in it:: echo "Hello {$to}!".PHP_EOL; } } - ?> -Then save the file to your application/controllers/ folder. +Then save the file to your *application/controllers/* folder. Now normally you would visit the your site using a URL similar to this:: @@ -60,19 +59,20 @@ in Windows and navigate to our CodeIgniter project. $ cd /path/to/project; $ php index.php tools message -If you did it right, you should see Hello World!. +If you did it right, you should see *Hello World!* printed. .. code-block:: bash $ php index.php tools message "John Smith" Here we are passing it a argument in the same way that URL parameters -work. "John Smith" is passed as a argument and output is: Hello John -Smith!. +work. "John Smith" is passed as a argument and output is:: + + Hello John Smith! That's it! ========== That, in a nutshell, is all there is to know about controllers on the command line. Remember that this is just a normal controller, so routing -and _remap works fine. +and ``_remap()`` works fine.
\ No newline at end of file diff --git a/user_guide_src/source/general/common_functions.rst b/user_guide_src/source/general/common_functions.rst index f3d48ac91..66dabd95e 100644 --- a/user_guide_src/source/general/common_functions.rst +++ b/user_guide_src/source/general/common_functions.rst @@ -6,59 +6,119 @@ CodeIgniter uses a few functions for its operation that are globally defined, and are available to you at any point. These do not require loading any libraries or helpers. -is_php('version_number') -======================== +is_php() +======== -is_php() determines of the PHP version being used is greater than the -supplied version_number. +.. php:function:: is_php($version = '5.3.0') -:: + :param string $version: Version number + :returns: bool - if (is_php('5.3.0')) +Determines of the PHP version being used is greater than the +supplied version number. + +Example:: + + if (is_php('5.3')) { - $str = quoted_printable_encode($str); + $str = quoted_printable_encode($str); } Returns boolean TRUE if the installed version of PHP is equal to or greater than the supplied version number. Returns FALSE if the installed version of PHP is lower than the supplied version number. -is_really_writable('path/to/file') -================================== +is_really_writable() +==================== + +.. php:function:: is_really_writeable($file) -is_writable() returns TRUE on Windows servers when you really can't + :param string $file: File path + :returns: bool + +``is_writable()`` returns TRUE on Windows servers when you really can't write to the file as the OS reports to PHP as FALSE only if the -read-only attribute is marked. This function determines if a file is -actually writable by attempting to write to it first. Generally only -recommended on platforms where this information may be unreliable. +read-only attribute is marked. + +This function determines if a file is actually writable by attempting +to write to it first. Generally only recommended on platforms where +this information may be unreliable. -:: +Example:: if (is_really_writable('file.txt')) { - echo "I could write to this if I wanted to"; + echo "I could write to this if I wanted to"; } else { - echo "File is not writable"; + echo "File is not writable"; } -config_item('item_key') -======================= +config_item() +============= + +.. php:function:: config_item($key) + + :param string $key: Config item key + :returns: mixed + +The :doc:`Config Library <../libraries/config>` is the preferred way of +accessing configuration information, however ``config_item()`` can be used +to retrieve single keys. See :doc:`Config Library <../libraries/config>` +documentation for more information. + +.. important:: This function only returns values set in your configuration + files. It does not take into account config values that are + dynamically set at runtime. + +show_error() +============ -The :doc:`Config library <../libraries/config>` is the preferred way of -accessing configuration information, however config_item() can be used -to retrieve single keys. See Config library documentation for more -information. +.. php:function:: show_error($message, $status_code, $heading = 'An Error Was Encountered') -show_error('message'), show_404('page'), log_message('level', 'message') -======================================================================== + :param mixed $message: Error message + :param int $status_code: HTTP Response status code + :param string $heading: Error page heading + :returns: void -These are each outlined on the :doc:`Error Handling <errors>` page. +This function calls ``CI_Exception::show_error()``. For more info, +please see the :doc:`Error Handling <errors>` documentation. -set_status_header(code, 'text') +show_404() +========== + +.. php:function:: show_404($page = '', $log_error = TRUE) + + :param string $page: URI string + :param bool $log_error: Whether to log the error + :returns: void + +This function calls ``CI_Exception::show_404()``. For more info, +please see the :doc:`Error Handling <errors>` documentation. + +log_message() +============= + +.. php:function:: log_message($level = 'error', $message, $php_error = FALSE) + + :param string $level: Log level + :param string $message: Message to log + :param bool $php_error: Whether we're loggin a native PHP error message + :returns: void + +This function is an alias for ``CI_Log::write_log()``. For more info, +please see the :doc:`Error Handling <errors>` documentation. + +set_status_header() =============================== +.. php:function:: set_status_header($code, $text = '') + + :param int $code: HTTP Reponse status code + :param string $text: A custom message to set with the status code + :returns: void + Permits you to manually set a server status header. Example:: set_status_header(401); @@ -67,26 +127,71 @@ 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. -remove_invisible_characters($str) -================================= +remove_invisible_characters() +============================= + +.. php:function:: remove_invisible_characters($str, $url_encoded = TRUE) + + :param string $str: Input string + :param bool $url_encoded: Whether to remove URL-encoded characters as well + :returns: string -This function prevents inserting null characters between ascii +This function prevents inserting NULL characters between ASCII characters, like Java\\0script. -html_escape($mixed) -=================== +Example:: + + remove_invisible_characters('Java\\0script'); + // Returns: 'Javascript' + +html_escape() +============= -This function provides short cut for ``htmlspecialchars()`` function. It -accepts string and array. To prevent Cross Site Scripting (XSS), it is -very useful. +.. php:function:: html_escape($var) + + :param mixed $var: Variable to escape + (string or array) + :returns: mixed + +This function acts as an alias for PHP's native ``htmlspecialchars()`` +function, with the advantage of being able to accept an array of strings. + +It is useful in preventing Cross Site Scripting (XSS). get_mimes() =========== -This function returns the MIMEs array *from config/mimes.php*. +.. php:function:: get_mimes() + + :returns: array + +This function returns a *reference* to the MIMEs array from +*application/config/mimes.php*. is_https() ========== +.. php:function:: is_https() + + :returns: bool + Returns TRUE if a secure (HTTPS) connection is used and FALSE -in any other case (including non-HTTP requests).
\ No newline at end of file +in any other case (including non-HTTP requests). + +function_usable($function_name) +=============================== + +.. php:function:: function_usable($function_name) + + :param string $function_name: Function name + :returns: bool + +Returns TRUE if a function exists and is usable, FALSE otherwise. + +This function runs a ``function_exists()`` check and if the +`Suhosin extension <http://www.hardened-php.net/suhosin/>` is loaded, +checks if it doesn't disable the function being checked. + +It is useful if you want to check for the availability of functions +such as ``eval()`` and ``exec()``, which are dangerous and might be +disabled on servers with highly restrictive security policies.
\ No newline at end of file diff --git a/user_guide_src/source/general/controllers.rst b/user_guide_src/source/general/controllers.rst index 6e5079419..729b08417 100644 --- a/user_guide_src/source/general/controllers.rst +++ b/user_guide_src/source/general/controllers.rst @@ -38,50 +38,49 @@ in it:: echo 'Hello World!'; } } - ?> -Then save the file to your application/controllers/ folder. +Then save the file to your *application/controllers/* directory. Now visit the your site using a URL similar to this:: example.com/index.php/blog/ -If you did it right, you should see Hello World!. +If you did it right, you should see: -Note: Class names must start with an uppercase letter. In other words, -this is valid:: + Hello World! + +.. important:: Class names must start with an uppercase letter. + +This is valid:: <?php class Blog extends CI_Controller { } - ?> - This is **not** valid:: <?php class blog extends CI_Controller { } - ?> Also, always make sure your controller extends the parent controller -class so that it can inherit all its functions. +class so that it can inherit all its methods. -Functions -========= +Methods +======= -In the above example the function name is index(). The "index" function +In the above example the method name is ``index()``. The "index" method is always loaded by default if the **second segment** of the URI is empty. Another way to show your "Hello World" message would be this:: example.com/index.php/blog/index/ -**The second segment of the URI determines which function in the +**The second segment of the URI determines which method in the controller gets called.** -Let's try it. Add a new function to your controller:: +Let's try it. Add a new method to your controller:: <?php class Blog extends CI_Controller { @@ -96,39 +95,37 @@ Let's try it. Add a new function to your controller:: echo 'Look at this!'; } } - ?> -Now load the following URL to see the comment function:: +Now load the following URL to see the comment method:: example.com/index.php/blog/comments/ You should see your new message. -Passing URI Segments to your Functions -====================================== +Passing URI Segments to your methods +==================================== If your URI contains more then two segments they will be passed to your -function as parameters. +method as parameters. For example, lets say you have a URI like this:: example.com/index.php/products/shoes/sandals/123 -Your function will be passed URI segments 3 and 4 ("sandals" and "123"):: +Your method will be passed URI segments 3 and 4 ("sandals" and "123"):: <?php class Products extends CI_Controller { - public function shoes($sandals, $id) - { - echo $sandals; - echo $id; - } + public function shoes($sandals, $id) + { + echo $sandals; + echo $id; + } } - ?> .. important:: If you are using the :doc:`URI Routing <routing>` - feature, the segments passed to your function will be the re-routed + feature, the segments passed to your method will be the re-routed ones. Defining a Default Controller @@ -139,59 +136,59 @@ present, as will be the case when only your site root URL is requested. To specify a default controller, open your **application/config/routes.php** file and set this variable:: - $route['default_controller'] = 'Blog'; + $route['default_controller'] = 'blog'; Where Blog is the name of the controller class you want used. If you now load your main index.php file without specifying any URI segments you'll see your Hello World message by default. -Remapping Function Calls -======================== +Remapping Method Calls +====================== As noted above, the second segment of the URI typically determines which -function in the controller gets called. CodeIgniter permits you to -override this behavior through the use of the _remap() function:: +method in the controller gets called. CodeIgniter permits you to override +this behavior through the use of the ``_remap()`` method:: public function _remap() { - // Some code here... + // Some code here... } -.. important:: If your controller contains a function named _remap(), +.. important:: If your controller contains a method named _remap(), it will **always** get called regardless of what your URI contains. It - overrides the normal behavior in which the URI determines which function - is called, allowing you to define your own function routing rules. + overrides the normal behavior in which the URI determines which method + is called, allowing you to define your own method routing rules. -The overridden function call (typically the second segment of the URI) -will be passed as a parameter to the _remap() function:: +The overridden method call (typically the second segment of the URI) will +be passed as a parameter to the ``_remap()`` method:: public function _remap($method) { - if ($method == 'some_method') - { - $this->$method(); - } - else - { - $this->default_method(); - } + if ($method === 'some_method') + { + $this->$method(); + } + else + { + $this->default_method(); + } } -Any extra segments after the method name are passed into _remap() as an +Any extra segments after the method name are passed into ``_remap()`` as an optional second parameter. This array can be used in combination with -PHP's `call_user_func_array <http://php.net/call_user_func_array>`_ +PHP's `call_user_func_array() <http://php.net/call_user_func_array>`_ to emulate CodeIgniter's default behavior. -:: +Example:: public function _remap($method, $params = array()) { - $method = 'process_'.$method; - if (method_exists($this, $method)) - { - return call_user_func_array(array($this, $method), $params); - } - show_404(); + $method = 'process_'.$method; + if (method_exists($this, $method)) + { + return call_user_func_array(array($this, $method), $params); + } + show_404(); } Processing Output @@ -199,69 +196,75 @@ Processing Output CodeIgniter has an output class that takes care of sending your final rendered data to the web browser automatically. More information on this -can be found in the :doc:`Views <views>` and :doc:`Output class <../libraries/output>` pages. In some cases, however, you -might want to post-process the finalized data in some way and send it to -the browser yourself. CodeIgniter permits you to add a function named -_output() to your controller that will receive the finalized output -data. +can be found in the :doc:`Views <views>` and :doc:`Output Class +<../libraries/output>` pages. In some cases, however, you might want to +post-process the finalized data in some way and send it to the browser +yourself. CodeIgniter permits you to add a method named ``_output()`` +to your controller that will receive the finalized output data. -.. important:: If your controller contains a function named _output(), - it will **always** be called by the output class instead of echoing the - finalized data directly. The first parameter of the function will - contain the finalized output. +.. important:: If your controller contains a method named ``_output()``, + it will **always** be called by the output class instead of + echoing the finalized data directly. The first parameter of the + method will contain the finalized output. Here is an example:: public function _output($output) { - echo $output; + echo $output; } -.. note:: Please note that your _output() function will receive the data in its - finalized state. Benchmark and memory usage data will be rendered, cache - files written (if you have caching enabled), and headers will be sent - (if you use that :doc:`feature <../libraries/output>`) before it is - handed off to the _output() function. - To have your controller's output cached properly, its _output() method - can use:: +.. note:: Please note that your ``_output()`` method will receive the + data in its finalized state. Benchmark and memory usage data + will be rendered, cache files written (if you have caching + enabled), and headers will be sent (if you use that + :doc:`feature <../libraries/output>`) before it is handed off + to the ``_output()`` method. + To have your controller's output cached properly, its + ``_output()`` method can use:: if ($this->output->cache_expiration > 0) { - $this->output->_write_cache($output); + $this->output->_write_cache($output); } - If you are using this feature the page execution timer and memory usage - stats might not be perfectly accurate since they will not take into - acccount any further processing you do. For an alternate way to control - output *before* any of the final processing is done, please see the - available methods in the :doc:`Output Class <../libraries/output>`. + If you are using this feature the page execution timer and + memory usage stats might not be perfectly accurate since they + will not take into account any further processing you do. + For an alternate way to control output *before* any of the + final processing is done, please see the available methods + in the :doc:`Output Library <../libraries/output>`. -Private Functions -================= +Private methods +=============== -In some cases you may want certain functions hidden from public access. -To make a function private, simply add an underscore as the name prefix -and it will not be served via a URL request. For example, if you were to -have a function like this:: +In some cases you may want certain methods hidden from public access. +In order to achieve this, simply declare the method as being private +or protected and it will not be served via a URL request. For example, +if you were to have a method like this:: private function _utility() { - // some code + // some code } Trying to access it via the URL, like this, will not work:: example.com/index.php/blog/_utility/ -Organizing Your Controllers into Sub-folders -============================================ +.. note:: Prefixing method names with an underscore will also prevent + them from being called. This is a legacy feature that is left + for backwards-compatibility. + +Organizing Your Controllers into Sub-directories +================================================ If you are building a large application you might find it convenient to -organize your controllers into sub-folders. CodeIgniter permits you to -do this. +organize your controllers into sub-directories. CodeIgniter permits you +to do this. -Simply create folders within your application/controllers directory and -place your controller classes within them. +Simply create folders within your *application/controllers/* directory +and place your controller classes within them. .. note:: When using this feature the first segment of your URI must specify the folder. For example, lets say you have a controller located @@ -273,9 +276,9 @@ place your controller classes within them. example.com/index.php/products/shoes/show/123 -Each of your sub-folders may contain a default controller which will be +Each of your sub-directories may contain a default controller which will be called if the URL contains only the sub-folder. Simply name your default -controller as specified in your application/config/routes.php file +controller as specified in your *application/config/routes.php* file. CodeIgniter also permits you to remap your URIs using its :doc:`URI Routing <routing>` feature. @@ -292,33 +295,38 @@ The reason this line is necessary is because your local constructor will be overriding the one in the parent controller class so we need to manually call it. -:: +Example:: <?php class Blog extends CI_Controller { - public function __construct() - { - parent::__construct(); - // Your own constructor code - } + public function __construct() + { + parent::__construct(); + // Your own constructor code + } } - ?> Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work. -Reserved Function Names -======================= +Reserved method names +===================== Since your controller classes will extend the main application -controller you must be careful not to name your functions identically to +controller you must be careful not to name your methods identically to the ones used by that class, otherwise your local functions will override them. See :doc:`Reserved Names <reserved_names>` for a full list. +.. important:: You should also never have a method named identically + to its class name. If you do, and there is no ``__construct()`` + method in the same class, then your e.g. ``Index::index()`` + method will be executed as a class constructor! This is a PHP4 + backwards-compatibility feature. + That's it! ========== -That, in a nutshell, is all there is to know about controllers. +That, in a nutshell, is all there is to know about controllers.
\ No newline at end of file diff --git a/user_guide_src/source/general/core_classes.rst b/user_guide_src/source/general/core_classes.rst index 4aa6693f7..ce57aeef0 100644 --- a/user_guide_src/source/general/core_classes.rst +++ b/user_guide_src/source/general/core_classes.rst @@ -39,9 +39,9 @@ Replacing Core Classes ====================== To use one of your own system classes instead of a default one simply -place your version inside your local application/core directory:: +place your version inside your local *application/core/* directory:: - application/core/some-class.php + application/core/some_class.php If this directory does not exist you can create it. @@ -59,7 +59,7 @@ Extending Core Class ==================== If all you need to do is add some functionality to an existing library - -perhaps add a function or two - then it's overkill to replace the entire +perhaps add a method or two - then it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: @@ -75,19 +75,19 @@ application/core/MY_Input.php, and declare your class with:: } -Note: If you need to use a constructor in your class make sure you +.. note:: If you need to use a constructor in your class make sure you extend the parent constructor:: class MY_Input extends CI_Input { - function __construct() - { - parent::__construct(); - } + public function __construct() + { + parent::__construct(); + } } **Tip:** Any functions in your class that are named identically to the -functions in the parent class will be used instead of the native ones +methods in the parent class will be used instead of the native ones (this is known as "method overriding"). This allows you to substantially alter the CodeIgniter core. @@ -98,24 +98,24 @@ your new class in your application controller's constructors. class Welcome extends MY_Controller { - function __construct() - { - parent::__construct(); - } + public function __construct() + { + parent::__construct(); + } - function index() - { - $this->load->view('welcome_message'); - } + public function index() + { + $this->load->view('welcome_message'); + } } Setting Your Own Prefix ----------------------- To set your own sub-class prefix, open your -application/config/config.php file and look for this item:: +*application/config/config.php* file and look for this item:: $config['subclass_prefix'] = 'MY_'; -Please note that all native CodeIgniter libraries are prefixed with CI\_ -so DO NOT use that as your prefix. +Please note that all native CodeIgniter libraries are prefixed +with CI\_ so DO NOT use that as your prefix.
\ No newline at end of file diff --git a/user_guide_src/source/general/creating_drivers.rst b/user_guide_src/source/general/creating_drivers.rst index 0e22e4f14..cf4ea5d7f 100644 --- a/user_guide_src/source/general/creating_drivers.rst +++ b/user_guide_src/source/general/creating_drivers.rst @@ -16,5 +16,6 @@ Sample driver directory and file structure layout: - Driver_name_subclass_2.php - Driver_name_subclass_3.php -**NOTE:** In order to maintain compatibility on case-sensitive file -systems, the Driver_name directory must be ucfirst() +.. note:: In order to maintain compatibility on case-sensitive + file systems, the Driver_name directory must be + named in the format returned by ``ucfirst()``.
\ No newline at end of file diff --git a/user_guide_src/source/general/creating_libraries.rst b/user_guide_src/source/general/creating_libraries.rst index 673fbd4bb..8bafd4532 100644 --- a/user_guide_src/source/general/creating_libraries.rst +++ b/user_guide_src/source/general/creating_libraries.rst @@ -12,7 +12,7 @@ your local resources and the global framework resources. As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing -identically named versions in your application/libraries folder. +identically named versions in your *application/libraries* directory. In summary: @@ -28,8 +28,8 @@ The page below explains these three concepts in detail. Storage ======= -Your library classes should be placed within your application/libraries -folder, as this is where CodeIgniter will look for them when they are +Your library classes should be placed within your *application/libraries* +directory, as this is where CodeIgniter will look for them when they are initialized. Naming Conventions @@ -49,9 +49,9 @@ Someclass purely as an example):: class Someclass { - public function some_function() - { - } + public function some_method() + { + } } /* End of file Someclass.php */ @@ -59,7 +59,7 @@ Someclass purely as an example):: Using Your Class ================ -From within any of your :doc:`Controller <controllers>` functions you +From within any of your :doc:`Controller <controllers>` methods you can initialize your class using the standard:: $this->load->library('someclass'); @@ -70,12 +70,12 @@ doesn't care. Once loaded you can access your class using the lower case version:: - $this->someclass->some_function(); // Object instances will always be lower case + $this->someclass->some_method(); // Object instances will always be lower case Passing Parameters When Initializing Your Class =============================================== -In the library loading function you can dynamically pass data as an +In the library loading method you can dynamically pass data as an array via the second parameter and it will be passed to your class constructor:: @@ -86,21 +86,19 @@ constructor:: If you use this feature you must set up your class constructor to expect data:: - <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Someclass { - public function __construct($params) - { - // Do something with $params - } + public function __construct($params) + { + // Do something with $params + } } - ?> - You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name and store it in -your application/config/ folder. Note that if you dynamically pass +your *application/config/* directory. Note that if you dynamically pass parameters as described above, the config file option will not be available. @@ -108,18 +106,18 @@ Utilizing CodeIgniter Resources within Your Library =================================================== To access CodeIgniter's native resources within your library use the -get_instance() function. This function returns the CodeIgniter super +``get_instance()`` method. This method returns the CodeIgniter super object. -Normally from within your controller functions you will call any of the -available CodeIgniter functions using the $this construct:: +Normally from within your controller methods you will call any of the +available CodeIgniter methods using the ``$this`` construct:: $this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url'); // etc. -$this, however, only works directly within your controllers, your +``$this``, however, only works directly within your controllers, your models, or your views. If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows: @@ -128,7 +126,7 @@ First, assign the CodeIgniter object to a variable:: $CI =& get_instance(); Once you've assigned the object to a variable, you'll use that variable -*instead* of $this:: +*instead* of ``$this``:: $CI =& get_instance(); @@ -137,7 +135,7 @@ Once you've assigned the object to a variable, you'll use that variable $CI->config->item('base_url'); // etc. -.. note:: You'll notice that the above get_instance() function is being +.. note:: You'll notice that the above ``get_instance()`` function is being passed by reference:: $CI =& get_instance(); @@ -145,6 +143,36 @@ Once you've assigned the object to a variable, you'll use that variable This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it. +However, since a library is a class, it would be better if you +take full advantage of the OOP principles. So, in order to +be able to use the CodeIgniter super-object in all of the class +methods, you're encouraged to assign it to a property instead:: + +class Example_library { + + protected $CI; + + // We'll use a constructor, as you can't directly call a function + // from a property definition. + public function __construct() + { + // Assign the CodeIgniter super-object + $this->CI =& get_instance(); + } + + public function foo() + { + $this->CI->load->helper('url'); + redirect(); + } + + public function bar() + { + echo $this->CI->config_item('base_url'); + } + +} + Replacing Native Libraries with Your Versions ============================================= @@ -152,8 +180,8 @@ Simply by naming your class files identically to a native library will cause CodeIgniter to use it instead of the native one. To use this feature you must name the file and the class declaration exactly the same as the native library. For example, to replace the native Email -library you'll create a file named application/libraries/Email.php, and -declare your class with:: +library you'll create a file named *application/libraries/Email.php*, +and declare your class with:: class CI_Email { @@ -161,7 +189,7 @@ declare your class with:: Note that most native classes are prefixed with CI\_. -To load your library you'll see the standard loading function:: +To load your library you'll see the standard loading method:: $this->load->library('email'); @@ -172,7 +200,7 @@ Extending Native Libraries ========================== If all you need to do is add some functionality to an existing library - -perhaps add a function or two - then it's overkill to replace the entire +perhaps add a method or two - then it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: @@ -182,7 +210,7 @@ couple exceptions: item is configurable. See below.). For example, to extend the native Email class you'll create a file named -application/libraries/MY_Email.php, and declare your class with:: +*application/libraries/MY_Email.php*, and declare your class with:: class MY_Email extends CI_Email { @@ -200,8 +228,7 @@ extend the parent constructor:: } -.. note:: - Not all of the libraries have the same (or any) parameters +.. note:: Not all of the libraries have the same (or any) parameters in their constructor. Take a look at the library that you're extending first to see how it should be implemented. @@ -218,15 +245,15 @@ Once loaded you will use the class variable as you normally would for the class you are extending. In the case of the email class all calls will use:: - $this->email->some_function(); + $this->email->some_method(); Setting Your Own Prefix ----------------------- To set your own sub-class prefix, open your -application/config/config.php file and look for this item:: +*application/config/config.php* file and look for this item:: $config['subclass_prefix'] = 'MY_'; Please note that all native CodeIgniter libraries are prefixed with CI\_ -so DO NOT use that as your prefix. +so DO NOT use that as your prefix.
\ No newline at end of file diff --git a/user_guide_src/source/general/credits.rst b/user_guide_src/source/general/credits.rst index 2c7459894..03ee83dd6 100644 --- a/user_guide_src/source/general/credits.rst +++ b/user_guide_src/source/general/credits.rst @@ -16,4 +16,4 @@ of the Reactor Team. A hat tip goes to Ruby on Rails for inspiring us to create a PHP framework, and for bringing frameworks into the general consciousness of -the web community. +the web community.
\ No newline at end of file diff --git a/user_guide_src/source/general/drivers.rst b/user_guide_src/source/general/drivers.rst index e2ded62e2..b64b0e75e 100644 --- a/user_guide_src/source/general/drivers.rst +++ b/user_guide_src/source/general/drivers.rst @@ -8,18 +8,18 @@ parent class, but not their siblings. Drivers provide an elegant syntax in your :doc:`controllers <controllers>` for libraries that benefit from or require being broken down into discrete classes. -Drivers are found in the system/libraries folder, in their own folder -which is identically named to the parent library class. Also inside that -folder is a subfolder named drivers, which contains all of the possible -child class files. +Drivers are found in the *system/libraries/* directory, in their own +sub-directory which is identically named to the parent library class. +Also inside that directory is a subdirectory named drivers, which +contains all of the possible child class files. To use a driver you will initialize it within a controller using the -following initialization function:: +following initialization method:: - $this->load->driver('class name'); + $this->load->driver('class_name'); Where class name is the name of the driver class you want to invoke. For -example, to load a driver named "Some Parent" you would do this:: +example, to load a driver named "Some_parent" you would do this:: $this->load->driver('some_parent'); @@ -37,4 +37,4 @@ Creating Your Own Drivers ========================= Please read the section of the user guide that discusses how to :doc:`create -your own drivers <creating_drivers>`. +your own drivers <creating_drivers>`.
\ No newline at end of file diff --git a/user_guide_src/source/general/environments.rst b/user_guide_src/source/general/environments.rst index fa1b096e2..d74ebb8d5 100644 --- a/user_guide_src/source/general/environments.rst +++ b/user_guide_src/source/general/environments.rst @@ -11,8 +11,8 @@ when "live". The ENVIRONMENT Constant ======================== -By default, CodeIgniter comes with the environment constant set to use -the value provided in ``$_SERVER['CI_ENV']``, otherwise defaults to +By default, CodeIgniter comes with the environment constant set to use +the value provided in ``$_SERVER['CI_ENV']``, otherwise defaults to 'development'. At the top of index.php, you will see:: define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development'); @@ -49,4 +49,4 @@ Optionally, you can have CodeIgniter load environment-specific configuration files. This may be useful for managing things like differing API keys across multiple environments. This is described in more detail in the environment section of the `Config -Class <../libraries/config.html#environments>`_ documentation. +Class <../libraries/config.html#environments>`_ documentation.
\ No newline at end of file diff --git a/user_guide_src/source/general/errors.rst b/user_guide_src/source/general/errors.rst index 91b59140f..8c941aadb 100644 --- a/user_guide_src/source/general/errors.rst +++ b/user_guide_src/source/general/errors.rst @@ -20,47 +20,69 @@ without having to worry about class/function scoping. The following functions let you generate errors: -show_error('message' [, int $status_code= 500 ] ) -=================================================== +show_error() +============ + +.. php:function:: show_error($message, $status_code, $heading = 'An Error Was Encountered') + + :param mixed $message: Error message + :param int $status_code: HTTP Response status code + :param string $heading: Error page heading + :returns: void This function will display the error message supplied to it using the -following error template: +following error template:: + + application/errors/error_general.php + +The optional parameter ``$status_code`` determines what HTTP status +code should be sent with the error. -application/errors/error_general.php +show_404() +========== -The optional parameter $status_code determines what HTTP status code -should be sent with the error. +.. php:function:: show_404($page = '', $log_error = TRUE) -show_404('page' [, 'log_error']) -================================== + :param string $page: URI string + :param bool $log_error: Whether to log the error + :returns: void This function will display the 404 error message supplied to it using -the following error template: +the following error template:: -application/errors/error_404.php + application/errors/error_404.php The function expects the string passed to it to be the file path to the page that isn't found. Note that CodeIgniter automatically shows 404 messages if controllers are not found. -CodeIgniter automatically logs any show_404() calls. Setting the +CodeIgniter automatically logs any ``show_404()`` calls. Setting the optional second parameter to FALSE will skip logging. -log_message('level', 'message') -================================ +log_message() +============= + +.. php:function:: log_message($level = 'error', $message, $php_error = FALSE) + + :param string $level: Log level + :param string $message: Message to log + :param bool $php_error: Whether we're loggin a native PHP error message + :returns: void This function lets you write messages to your log files. You must supply one of three "levels" in the first parameter, indicating what type of message it is (debug, error, info), with the message itself in the -second parameter. Example:: +second parameter. + +Example:: - if ($some_var == "") + if ($some_var == '') { - log_message('error', 'Some variable did not contain a value.'); + log_message('error', 'Some variable did not contain a value.'); } else { - log_message('debug', 'Some variable was correctly set'); + log_message('debug', 'Some variable was correctly set'); } log_message('info', 'The purpose of some variable is to provide some value.'); @@ -77,8 +99,8 @@ There are three message types: natively generate any info messages but you may want to in your application. -.. note:: In order for the log file to actually be written, the "logs" - folder must be writable. In addition, you must set the "threshold" for - logging in application/config/config.php. You might, for example, only - want error messages to be logged, and not the other two types. If you - set it to zero logging will be disabled. +.. note:: In order for the log file to actually be written, the *logs* + directory must be writable. In addition, you must set the "threshold" + for logging in *application/config/config.php*. You might, for example, + only want error messages to be logged, and not the other two types. + If you set it to zero logging will be disabled.
\ No newline at end of file diff --git a/user_guide_src/source/general/helpers.rst b/user_guide_src/source/general/helpers.rst index 3a98311a6..d171aa8ed 100644 --- a/user_guide_src/source/general/helpers.rst +++ b/user_guide_src/source/general/helpers.rst @@ -23,12 +23,12 @@ Helpers are typically stored in your **system/helpers**, or **application/helpers directory**. CodeIgniter will look first in your **application/helpers directory**. If the directory does not exist or the specified helper is not located there CI will instead look in your -global system/helpers folder. +global *system/helpers/* directory. Loading a Helper ================ -Loading a helper file is quite simple using the following function:: +Loading a helper file is quite simple using the following method:: $this->load->helper('name'); @@ -40,15 +40,15 @@ For example, to load the **URL Helper** file, which is named $this->load->helper('url'); -A helper can be loaded anywhere within your controller functions (or +A helper can be loaded anywhere within your controller methods (or even within your View files, although that's not a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it. -Note: The Helper loading function above does not return a value, so -don't try to assign it to a variable. Just use it as shown. +.. note:: The Helper loading method above does not return a value, so + don't try to assign it to a variable. Just use it as shown. Loading Multiple Helpers ======================== @@ -56,14 +56,16 @@ Loading Multiple Helpers If you need to load more than one helper you can specify them in an array, like this:: - $this->load->helper( array('helper1', 'helper2', 'helper3') ); + $this->load->helper( + array('helper1', 'helper2', 'helper3') + ); Auto-loading Helpers ==================== If you find that you need a particular helper globally throughout your application, you can tell CodeIgniter to auto-load it during system -initialization. This is done by opening the **application/config/autoload.php** +initialization. This is done by opening the **application/config/autoload.php** file and adding the helper to the autoload array. Using a Helper @@ -72,13 +74,13 @@ Using a Helper Once you've loaded the Helper File containing the function you intend to use, you'll call it the way you would a standard PHP function. -For example, to create a link using the anchor() function in one of your -view files you would do this:: +For example, to create a link using the ``anchor()`` function in one of +your view files you would do this:: <?php echo anchor('blog/comments', 'Click Here');?> Where "Click Here" is the name of the link, and "blog/comments" is the -URI to the controller/function you wish to link to. +URI to the controller/method you wish to link to. "Extending" Helpers =================== @@ -91,11 +93,11 @@ If all you need to do is add some functionality to an existing helper - perhaps add a function or two, or change how a particular helper function operates - then it's overkill to replace the entire helper with your version. In this case it's better to simply "extend" the Helper. -The term "extend" is used loosely since Helper functions are procedural -and discrete and cannot be extended in the traditional programmatic -sense. Under the hood, this gives you the ability to add to the -functions a Helper provides, or to modify how the native Helper -functions operate. + +.. note:: The term "extend" is used loosely since Helper functions are + procedural and discrete and cannot be extended in the traditional + programmatic sense. Under the hood, this gives you the ability to + add to or or to replace the functions a Helper provides. For example, to extend the native **Array Helper** you'll create a file named **application/helpers/MY_array_helper.php**, and add or override @@ -104,31 +106,31 @@ functions:: // any_in_array() is not in the Array Helper, so it defines a new function function any_in_array($needle, $haystack) { - $needle = (is_array($needle)) ? $needle : array($needle); - - foreach ($needle as $item) - { - if (in_array($item, $haystack)) - { - return TRUE; - } + $needle = is_array($needle) ? $needle : array($needle); + + foreach ($needle as $item) + { + if (in_array($item, $haystack)) + { + return TRUE; + } } - return FALSE; + return FALSE; } // random_element() is included in Array Helper, so it overrides the native function function random_element($array) { - shuffle($array); - return array_pop($array); + shuffle($array); + return array_pop($array); } Setting Your Own Prefix ----------------------- The filename prefix for "extending" Helpers is the same used to extend -libraries and Core classes. To set your own prefix, open your +libraries and core classes. To set your own prefix, open your **application/config/config.php** file and look for this item:: $config['subclass_prefix'] = 'MY_'; @@ -140,4 +142,4 @@ Now What? ========= In the Table of Contents you'll find a list of all the available Helper -Files. Browse each one to see what they do. +Files. Browse each one to see what they do.
\ No newline at end of file diff --git a/user_guide_src/source/general/hooks.rst b/user_guide_src/source/general/hooks.rst index 65696f6c7..fc5da5b80 100644 --- a/user_guide_src/source/general/hooks.rst +++ b/user_guide_src/source/general/hooks.rst @@ -16,25 +16,26 @@ Enabling Hooks ============== The hooks feature can be globally enabled/disabled by setting the -following item in the application/config/config.php file:: +following item in the **application/config/config.php** file:: $config['enable_hooks'] = TRUE; Defining a Hook =============== -Hooks are defined in application/config/hooks.php file. Each hook is -specified as an array with this prototype:: +Hooks are defined in **application/config/hooks.php** file. +Each hook is specified as an array with this prototype:: $hook['pre_controller'] = array( - 'class' => 'MyClass', - 'function' => 'Myfunction', - 'filename' => 'Myclass.php', - 'filepath' => 'hooks', - 'params' => array('beer', 'wine', 'snacks') - ); + 'class' => 'MyClass', + 'function' => 'Myfunction', + 'filename' => 'Myclass.php', + 'filepath' => 'hooks', + 'params' => array('beer', 'wine', 'snacks') + ); **Notes:** + The array index correlates to the name of the particular hook point you want to use. In the above example the hook point is pre_controller. A list of hook points is found below. The following items should be @@ -42,14 +43,15 @@ defined in your associative hook array: - **class** The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class, leave this item blank. -- **function** The function name you wish to call. +- **function** The function (or method) name you wish to call. - **filename** The file name containing your class/function. -- **filepath** The name of the directory containing your script. Note: - Your script must be located in a directory INSIDE your application - folder, so the file path is relative to that folder. For example, if - your script is located in application/hooks, you will simply use - hooks as your filepath. If your script is located in - application/hooks/utilities you will use hooks/utilities as your +- **filepath** The name of the directory containing your script. + Note: + Your script must be located in a directory INSIDE your *application/* + directory, so the file path is relative to that directory. For example, + if your script is located in *application/hooks/*, you will simply use + 'hooks' as your filepath. If your script is located in + *application/hooks/utilities/* you will use 'hooks/utilities' as your filepath. No trailing slash. - **params** Any parameters you wish to pass to your script. This item is optional. @@ -61,20 +63,20 @@ If want to use the same hook point with more then one script, simply make your array declaration multi-dimensional, like this:: $hook['pre_controller'][] = array( - 'class' => 'MyClass', - 'function' => 'Myfunction', - 'filename' => 'Myclass.php', - 'filepath' => 'hooks', - 'params' => array('beer', 'wine', 'snacks') - ); + 'class' => 'MyClass', + 'function' => 'MyMethod', + 'filename' => 'Myclass.php', + 'filepath' => 'hooks', + 'params' => array('beer', 'wine', 'snacks') + ); $hook['pre_controller'][] = array( - 'class' => 'MyOtherClass', - 'function' => 'MyOtherfunction', - 'filename' => 'Myotherclass.php', - 'filepath' => 'hooks', - 'params' => array('red', 'yellow', 'blue') - ); + 'class' => 'MyOtherClass', + 'function' => 'MyOtherMethod', + 'filename' => 'Myotherclass.php', + 'filepath' => 'hooks', + 'params' => array('red', 'yellow', 'blue') + ); Notice the brackets after each array index:: @@ -101,18 +103,17 @@ The following is a list of available hook points. - **post_controller** Called immediately after your controller is fully executed. - **display_override** - Overrides the _display() function, used to send the finalized page + Overrides the ``_display()`` method, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to - reference the CI superobject with $this->CI =& get_instance() and + reference the CI superobject with ``$this->CI =& get_instance()`` and then the finalized data will be available by calling - $this->CI->output->get_output() + ``$this->CI->output->get_output()``. - **cache_override** - Enables you to call your own function instead of the - _display_cache() function in the output class. This permits you to - use your own cache display mechanism. + Enables you to call your own method instead of the ``_display_cache()`` + method in the :doc:`Output Library <../libraries/output>`. This permits + you to use your own cache display mechanism. - **post_system** Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the - browser. - + browser.
\ No newline at end of file diff --git a/user_guide_src/source/general/index.rst b/user_guide_src/source/general/index.rst index 2162b8140..2bc684a1d 100644 --- a/user_guide_src/source/general/index.rst +++ b/user_guide_src/source/general/index.rst @@ -29,4 +29,4 @@ General Topics environments alternative_php security - PHP Style Guide <styleguide> + PHP Style Guide <styleguide>
\ No newline at end of file diff --git a/user_guide_src/source/general/libraries.rst b/user_guide_src/source/general/libraries.rst index 954a5b8f8..6e1c8b6dd 100644 --- a/user_guide_src/source/general/libraries.rst +++ b/user_guide_src/source/general/libraries.rst @@ -2,30 +2,31 @@ Using CodeIgniter Libraries ########################### -All of the available libraries are located in your system/libraries -folder. In most cases, to use one of these classes involves initializing +All of the available libraries are located in your *system/libraries/* +directory. In most cases, to use one of these classes involves initializing it within a :doc:`controller <controllers>` using the following -initialization function:: +initialization method:: - $this->load->library('class name'); + $this->load->library('class_name'); -Where class name is the name of the class you want to invoke. For -example, to load the form validation class you would do this:: +Where 'class_name' is the name of the class you want to invoke. For +example, to load the :doc:`Form Validation Library +<../libraries/form_validation>` you would do this:: - $this->load->library('form_validation'); + $this->load->library('form_validation'); Once initialized you can use it as indicated in the user guide page corresponding to that class. Additionally, multiple libraries can be loaded at the same time by -passing an array of libraries to the load function. +passing an array of libraries to the load method. -:: +Example:: $this->load->library(array('email', 'table')); Creating Your Own Libraries =========================== -Please read the section of the user guide that discusses how to :doc:`create -your own libraries <creating_libraries>` +Please read the section of the user guide that discusses how to +:doc:`create your own libraries <creating_libraries>`. diff --git a/user_guide_src/source/general/managing_apps.rst b/user_guide_src/source/general/managing_apps.rst index 996481354..afb1aba2e 100644 --- a/user_guide_src/source/general/managing_apps.rst +++ b/user_guide_src/source/general/managing_apps.rst @@ -3,41 +3,39 @@ Managing your Applications ########################## By default it is assumed that you only intend to use CodeIgniter to -manage one application, which you will build in your application/ +manage one application, which you will build in your *application/* directory. It is possible, however, to have multiple sets of applications that share a single CodeIgniter installation, or even to -rename or relocate your application folder. +rename or relocate your application directory. -Renaming the Application Folder -=============================== - -If you would like to rename your application folder you may do so as -long as you open your main index.php file and set its name using the -$application_folder variable:: +Renaming the Application Directory +================================== - $application_folder = "application"; +If you would like to rename your application directory you may do so +as long as you open your main index.php file and set its name using +the ``$application_folder`` variable:: -Relocating your Application Folder -================================== + $application_folder = 'application'; -It is possible to move your application folder to a different location -on your server than your system folder. To do so open your main -index.php and set a *full server path* in the $application_folder -variable. +Relocating your Application Directory +===================================== -:: +It is possible to move your application directory to a different +location on your server than your system directory. To do so open +your main index.php and set a *full server path* in the +``$application_folder`` variable:: - $application_folder = "/Path/to/your/application"; + $application_folder = '/path/to/your/application'; Running Multiple Applications with one CodeIgniter Installation =============================================================== If you would like to share a common CodeIgniter installation to manage several different applications simply put all of the directories located -inside your application folder into their own sub-folder. +inside your application directory into their own sub-directory. -For example, let's say you want to create two applications, "foo" and -"bar". You could structure your application folders like this:: +For example, let's say you want to create two applications, named "foo" +and "bar". You could structure your application directories like this:: applications/foo/ applications/foo/config/ @@ -55,11 +53,11 @@ For example, let's say you want to create two applications, "foo" and applications/bar/views/ To select a particular application for use requires that you open your -main index.php file and set the $application_folder variable. For +main index.php file and set the ``$application_folder`` variable. For example, to select the "foo" application for use you would do this:: - $application_folder = "applications/foo"; + $application_folder = 'applications/foo'; .. note:: Each of your applications will need its own index.php file which calls the desired application. The index.php file can be named - anything you want. + anything you want.
\ No newline at end of file diff --git a/user_guide_src/source/general/models.rst b/user_guide_src/source/general/models.rst index 4e52a9648..a028a9569 100644 --- a/user_guide_src/source/general/models.rst +++ b/user_guide_src/source/general/models.rst @@ -18,55 +18,56 @@ model class might look like:: class Blog_model extends CI_Model { - public $title = ''; - public $content = ''; - public $date = ''; - - function __construct() - { - // Call the Model constructor - parent::__construct(); - } - - function get_last_ten_entries() - { - $query = $this->db->get('entries', 10); - return $query->result(); - } - - function insert_entry() - { - $this->title = $_POST['title']; // please read the below note - $this->content = $_POST['content']; - $this->date = time(); - - $this->db->insert('entries', $this); - } - - function update_entry() - { - $this->title = $_POST['title']; - $this->content = $_POST['content']; - $this->date = time(); - - $this->db->update('entries', $this, array('id' => $_POST['id'])); - } + public $title; + public $content; + public $date; + + public function __construct() + { + // Call the CI_Model constructor + parent::__construct(); + } + + public function get_last_ten_entries() + { + $query = $this->db->get('entries', 10); + return $query->result(); + } + + public function insert_entry() + { + $this->title = $_POST['title']; // please read the below note + $this->content = $_POST['content']; + $this->date = time(); + + $this->db->insert('entries', $this); + } + + public function update_entry() + { + $this->title = $_POST['title']; + $this->content = $_POST['content']; + $this->date = time(); + + $this->db->update('entries', $this, array('id' => $_POST['id'])); + } } -.. note:: The functions in the above example use the :doc:`Active - Record <../database/query_builder>` database functions. +.. note:: The methods in the above example use the :doc:`Query Builder + <../database/query_builder>` database methods. -.. note:: For the sake of simplicity in this example we're using $_POST +.. note:: For the sake of simplicity in this example we're using ``$_POST`` directly. This is generally bad practice, and a more common approach - would be to use the :doc:`Input Class <../libraries/input>` - $this->input->post('title') + would be to use the :doc:`Input Library <../libraries/input>` + ``$this->input->post('title')``. Anatomy of a Model ================== -Model classes are stored in your **application/models/ folder**. They can be -nested within sub-folders if you want this type of organization. +Model classes are stored in your **application/models/** directory. +They can be nested within sub-directories if you want this type of +organization. The basic prototype for a model class is this:: @@ -103,14 +104,14 @@ Loading a Model =============== Your models will typically be loaded and called from within your -:doc:`controller <controllers>` functions. To load a model you will use +:doc:`controller <controllers>` methods. To load a model you will use the following method:: $this->load->model('model_name'); -If your model is located in a sub-folder, include the relative path from -your models folder. For example, if you have a model located at -application/models/blog/queries.php you'll load it using:: +If your model is located in a sub-directory, include the relative path +from your models directory. For example, if you have a model located at +*application/models/blog/queries.php* you'll load it using:: $this->load->model('blog/queries'); @@ -141,7 +142,6 @@ view:: $this->load->view('blog', $data); } - } @@ -163,10 +163,9 @@ database. The following options for connecting are available to you: - You can connect using the standard database methods :doc:`described here <../database/connecting>`, either from within your Controller class or your Model class. -- You can tell the model loading function to auto-connect by passing - TRUE (boolean) via the third parameter, and connectivity settings, as - defined in your database config file will be used: - :: +- You can tell the model loading method to auto-connect by passing + TRUE (boolean) via the third parameter, and connectivity settings, + as defined in your database config file will be used:: $this->load->model('model_name', '', TRUE); diff --git a/user_guide_src/source/general/profiling.rst b/user_guide_src/source/general/profiling.rst index 437635289..6dbd0be16 100644 --- a/user_guide_src/source/general/profiling.rst +++ b/user_guide_src/source/general/profiling.rst @@ -3,7 +3,7 @@ Profiling Your Application ########################## The Profiler Class will display benchmark results, queries you have run, -and $_POST data at the bottom of your pages. This information can be +and ``$_POST`` data at the bottom of your pages. This information can be useful during development in order to help with debugging and optimization. @@ -11,14 +11,14 @@ Initializing the Class ====================== .. important:: This class does NOT need to be initialized. It is loaded - automatically by the :doc:`Output Class <../libraries/output>` if - profiling is enabled as shown below. + automatically by the :doc:`Output Library <../libraries/output>` + if profiling is enabled as shown below. Enabling the Profiler ===================== -To enable the profiler place the following function anywhere within your -:doc:`Controller <controllers>` functions:: +To enable the profiler place the following line anywhere within your +:doc:`Controller <controllers>` methods:: $this->output->enable_profiler(TRUE); @@ -35,8 +35,8 @@ Setting Benchmark Points In order for the Profiler to compile and display your benchmark data you must name your mark points using specific syntax. -Please read the information on setting Benchmark points in :doc:`Benchmark -Class <../libraries/benchmark>` page. +Please read the information on setting Benchmark points in the +:doc:`Benchmark Library <../libraries/benchmark>` page. Enabling and Disabling Profiler Sections ======================================== @@ -44,21 +44,21 @@ Enabling and Disabling Profiler Sections Each section of Profiler data can be enabled or disabled by setting a corresponding config variable to TRUE or FALSE. This can be done one of two ways. First, you can set application wide defaults with the -application/config/profiler.php config file. +*application/config/profiler.php* config file. -:: +Example:: $config['config'] = FALSE; $config['queries'] = FALSE; In your controllers, you can override the defaults and config file -values by calling the set_profiler_sections() method of the :doc:`Output -class <../libraries/output>`:: +values by calling the ``set_profiler_sections()`` method of the +:doc:`Output Library <../libraries/output>`:: $sections = array( - 'config' => TRUE, - 'queries' => TRUE - ); + 'config' => TRUE, + 'queries' => TRUE + ); $this->output->set_profiler_sections($sections); diff --git a/user_guide_src/source/general/requirements.rst b/user_guide_src/source/general/requirements.rst index d9edfba6d..104923625 100644 --- a/user_guide_src/source/general/requirements.rst +++ b/user_guide_src/source/general/requirements.rst @@ -3,7 +3,13 @@ Server Requirements ################### - `PHP <http://www.php.net/>`_ version 5.2.4 or newer. -- A Database is required for most web application programming. Current - supported databases are MySQL (5.1+), MySQLi, Oracle, PostgreSQL, - MS SQL, SQLSRV (SQL Server 2005+), SQLite, SQLite3, CUBRID, Interbase, - ODBC and PDO. +- A Database is required for most web application programming. + Currently supported databases are: + - MySQL (5.1+) via the *mysql* (deprecated), *mysqli* and *pdo* drivers + - Oracle via the *oci8* and *pdo* drivers + - PostgreSQL via the *postgre* and *pdo* drivers + - MS SQL via the *mssql*, *sqlsrv* (version 2005 and above only) and *pdo* drivers + - SQLite via the *sqlite* (version 2), *sqlite3* (version 3) and *pdo* drivers + - CUBRID via the *cubrid* and *pdo* drivers + - Interbase/Firebird via the *ibase* and *pdo* drivers + - ODBC via the *odbc* and *pdo* drivers (you should know that ODBC is actually an abstraction layer)
\ No newline at end of file diff --git a/user_guide_src/source/general/reserved_names.rst b/user_guide_src/source/general/reserved_names.rst index 3354375c5..d91292363 100644 --- a/user_guide_src/source/general/reserved_names.rst +++ b/user_guide_src/source/general/reserved_names.rst @@ -2,16 +2,17 @@ Reserved Names ############## -In order to help out, CodeIgniter uses a series of functions and names -in its operation. Because of this, some names cannot be used by a -developer. Following is a list of reserved names that cannot be used. +In order to help out, CodeIgniter uses a series of function, method, +class and variable names in its operation. Because of this, some names +cannot be used by a developer. Following is a list of reserved names +that cannot be used. Controller names ---------------- Since your controller classes will extend the main application -controller you must be careful not to name your functions identically to -the ones used by that class, otherwise your local functions will +controller you must be careful not to name your methods identically to +the ones used by that class, otherwise your local methods will override them. The following is a list of reserved names. Do not name your controller any of these: @@ -24,22 +25,25 @@ your controller any of these: Functions --------- -- is_really_writable() -- load_class() -- get_config() -- config_item() -- show_error() -- show_404() -- log_message() -- _exception_handler() -- get_instance() +- :php:func:`is_really_writable()` +- ``load_class()`` +- ``get_config()`` +- :php:func:`config_item()` +- :php:func:`show_error()` +- :php:func:`show_404()` +- :php:func:`log_message()` +- :php:func:`get_mimes()` +- :php:func:`html_escape()` +- :php:func:`get_instance()` +- ``_exception_handler()`` +- ``_stringify_attributes()`` Variables --------- -- $config -- $mimes -- $lang +- ``$config`` +- ``$db`` +- ``$lang`` Constants --------- @@ -62,5 +66,4 @@ Constants - FOPEN_WRITE_CREATE - FOPEN_READ_WRITE_CREATE - FOPEN_WRITE_CREATE_STRICT -- FOPEN_READ_WRITE_CREATE_STRICT - +- FOPEN_READ_WRITE_CREATE_STRICT
\ No newline at end of file diff --git a/user_guide_src/source/general/routing.rst b/user_guide_src/source/general/routing.rst index a6332c90c..2a0332088 100644 --- a/user_guide_src/source/general/routing.rst +++ b/user_guide_src/source/general/routing.rst @@ -9,34 +9,34 @@ normally follow this pattern:: example.com/class/function/id/ In some instances, however, you may want to remap this relationship so -that a different class/function can be called instead of the one +that a different class/method can be called instead of the one corresponding to the URL. -For example, lets say you want your URLs to have this prototype: +For example, lets say you want your URLs to have this prototype:: -example.com/product/1/ -example.com/product/2/ -example.com/product/3/ -example.com/product/4/ + example.com/product/1/ + example.com/product/2/ + example.com/product/3/ + example.com/product/4/ -Normally the second segment of the URL is reserved for the function -name, but in the example above it instead has a product ID. To overcome -this, CodeIgniter allows you to remap the URI handler. +Normally the second segment of the URL is reserved for the method +name, but in the example above it instead has a product ID. To +overcome this, CodeIgniter allows you to remap the URI handler. Setting your own routing rules ============================== -Routing rules are defined in your application/config/routes.php file. In -it you'll see an array called $route that permits you to specify your -own routing criteria. Routes can either be specified using wildcards or -Regular Expressions. +Routing rules are defined in your *application/config/routes.php* file. +In it you'll see an array called ``$route`` that permits you to specify +your own routing criteria. Routes can either be specified using wildcards +or Regular Expressions. Wildcards ========= A typical wildcard route might look something like this:: - $route['product/:num'] = "catalog/product_lookup"; + $route['product/:num'] = 'catalog/product_lookup'; In a route, the array key contains the URI to be matched, while the array value contains the destination it should be re-routed to. In the @@ -66,21 +66,21 @@ Examples Here are a few routing examples:: - $route['journals'] = "blogs"; + $route['journals'] = 'blogs'; A URL containing the word "journals" in the first segment will be remapped to the "blogs" class. :: - $route['blog/joe'] = "blogs/users/34"; + $route['blog/joe'] = 'blogs/users/34'; A URL containing the segments blog/joe will be remapped to the "blogs" class and the "users" method. The ID will be set to "34". :: - $route['product/(:any)'] = "catalog/product_lookup"; + $route['product/(:any)'] = 'catalog/product_lookup'; A URL with "product" as the first segment, and anything in the second will be remapped to the "catalog" class and the "product_lookup" @@ -88,12 +88,12 @@ method. :: - $route['product/(:num)'] = "catalog/product_lookup_by_id/$1"; + $route['product/(:num)'] = 'catalog/product_lookup_by_id/$1'; A URL with "product" as the first segment, and a number in the second will be remapped to the "catalog" class and the "product_lookup_by_id" method passing in the match as a variable to -the function. +the method. .. important:: Do not use leading/trailing slashes. @@ -111,7 +111,7 @@ A typical RegEx route might look something like this:: $route['products/([a-z]+)/(\d+)'] = '$1/id_$2'; In the above example, a URI similar to products/shirts/123 would instead -call the shirts controller class and the id_123 method. +call the "shirts" controller class and the "id_123" method. With regular expressions, you can also catch a segment containing a forward slash ('/'), which would usually represent the delimiter between @@ -122,7 +122,7 @@ page after they log in, you may find this example useful:: $route['login/(.+)'] = 'auth/login/$1'; -That will call the auth controller class and its ``login()`` method, +That will call the "auth" controller class and its ``login()`` method, passing everything contained in the URI after *login/* as a parameter. For those of you who don't know regular expressions and want to learn @@ -131,6 +131,17 @@ might be a good starting point. ..note:: You can also mix and match wildcards with regular expressions. +Callbacks +========= + +If you are using PHP >= 5.3 you can use callbacks in place of the normal +routing rules to process the back-references. Example:: + + $route['products/([a-z]+)/edit/(\d+)'] = function ($product_type, $id) + { + return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id; + }; + Reserved Routes =============== @@ -150,9 +161,9 @@ appear by default. This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 -error page. It won't affect to the show_404() function, which will -continue loading the default error_404.php file at -application/errors/error_404.php. +error page. It won't affect to the ``show_404()`` function, which will +continue loading the default *error_404.php* file at +*application/errors/error_404.php*. .. important:: The reserved routes must come before any wildcard or - regular expression routes. + regular expression routes.
\ No newline at end of file diff --git a/user_guide_src/source/general/security.rst b/user_guide_src/source/general/security.rst index 4d7a213d1..984ca840b 100644 --- a/user_guide_src/source/general/security.rst +++ b/user_guide_src/source/general/security.rst @@ -13,38 +13,40 @@ in your URI strings in order to help minimize the possibility that malicious data can be passed to your application. URIs may only contain the following: -- Alpha-numeric text +- Alpha-numeric text (latin characters only) - Tilde: ~ - Period: . - Colon: : - Underscore: \_ - Dash: - +- Pipe: | Register_globals ================= During system initialization all global variables are unset, except -those found in the $_GET, $_POST, and $_COOKIE arrays. The unsetting -routine is effectively the same as register_globals = off. +those found in the ``$_GET``, ``$_POST``, and ``$_COOKIE`` arrays. +The unsetting routine is effectively the same as +*register_globals = off*. -error_reporting -================ +display_errors +============== -In production environments, it is typically desirable to disable PHP's -error reporting by setting the internal error_reporting flag to a value +In production environments, it is typically desirable to "disable" PHP's +error reporting by setting the internal *display_errors* flag to a value of 0. This disables native PHP errors from being rendered as output, which may potentially contain sensitive information. Setting CodeIgniter's **ENVIRONMENT** constant in index.php to a value of **\'production\'** will turn off these errors. In development mode, it is recommended that a value of 'development' is used. More information -about differentiating between environments can be found on the :doc:`Handling -Environments <environments>` page. +about differentiating between environments can be found on the +:doc:`Handling Environments <environments>` page. magic_quotes_runtime -====================== +==================== -The magic_quotes_runtime directive is turned off during system +The *magic_quotes_runtime* directive is turned off during system initialization so that you don't have to remove slashes when retrieving data from your database. @@ -68,7 +70,7 @@ XSS Filtering ============= CodeIgniter comes with a Cross Site Scripting filter. This filter -looks for commonly used techniques to embed malicious Javascript into +looks for commonly used techniques to embed malicious JavaScript into your data, or other types of code that attempt to hijack cookies or do other malicious things. The XSS Filter is described :doc:`here <../libraries/security>`. @@ -76,15 +78,32 @@ do other malicious things. The XSS Filter is described Validate the data ================= -CodeIgniter has a :doc:`Form Validation -Class <../libraries/form_validation>` that assists you in +CodeIgniter has a :doc:`Form Validation Library +<../libraries/form_validation>` that assists you in validating, filtering, and prepping your data. Escape all data before database insertion ========================================= Never insert information into your database without escaping it. -Please see the section that discusses -:doc:`queries <../database/queries>` for more information. +Please see the section that discusses :doc:`database queries +<../database/queries>` for more information. +Hide your files +=============== +Another good security practice is to only leave your *index.php* +and "assets" (e.g. .js, css and image files) under your server's +*webroot* directory (most commonly named "htdocs/"). These are +the only files that you would need to be accessible from the web. + +Allowing your visitors to see anything else would potentially +allow them to access sensitive data, execute scripts, etc. + +If you're not allowed to do that, you can try using a .htaccess +file to restrict access to those resources. + +CodeIgniter will have an index.html file in all of its +directories in an attempt to hide some of this data, but have +it in mind that this is not enough to prevent a serious +attacker.
\ No newline at end of file diff --git a/user_guide_src/source/general/styleguide.rst b/user_guide_src/source/general/styleguide.rst index 925954c03..7c0a59791 100644 --- a/user_guide_src/source/general/styleguide.rst +++ b/user_guide_src/source/general/styleguide.rst @@ -168,11 +168,11 @@ picked up by IDEs:: /** * Encodes string for use in XML * - * @param string + * @param string $str Input string * @return string */ function xml_encode($str) - + :: /** @@ -180,9 +180,7 @@ picked up by IDEs:: * * @var array */ - public $data - - + public $data = array(); Use single line comments within code, leaving a blank line between large comment blocks and code. @@ -308,8 +306,8 @@ Use **===** and **!==** as necessary. } -See also information regarding -`typecasting <http://us3.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting>`_, +See also information regarding `typecasting +<http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting>`_, which can be quite useful. Typecasting has a slightly different effect which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables become empty strings, 0 (and @@ -338,7 +336,6 @@ begin before CodeIgniter outputs its content, leading to errors and an inability for CodeIgniter to send proper headers. In the examples below, select the text with your mouse to reveal the incorrect whitespace. - Compatibility ============= @@ -559,16 +556,16 @@ code abstraction, should be prefixed with an underscore. :: - convert_text() // public method - _convert_text() // private method + public function convert_text() + private function _convert_text() PHP Errors ========== Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance, never access a variable -that you did not set yourself (such as $_POST array keys) without first -checking to see that it isset(). +that you did not set yourself (such as ``$_POST`` array keys) without first +checking to see that it ``isset()``. Make sure that while developing your add-on, error reporting is enabled for ALL users, and that display_errors is enabled in the PHP @@ -579,22 +576,22 @@ environment. You can check this setting with:: exit "Enabled"; } -On some servers where display_errors is disabled, and you do not have +On some servers where *display_errors* is disabled, and you do not have the ability to change this in the php.ini, you can often enable it with:: ini_set('display_errors', 1); -**NOTE:** Setting the -`display_errors <http://us.php.net/manual/en/ref.errorfunc.php#ini.display-errors>`_ -setting with ini_set() at runtime is not identical to having it enabled -in the PHP environment. Namely, it will not have any effect if the -script has fatal errors +.. note:: Setting the `display_errors + <http://php.net/manual/en/ref.errorfunc.php#ini.display-errors>`_ + setting with ``ini_set()`` at runtime is not identical to having + it enabled in the PHP environment. Namely, it will not have any + effect if the script has fatal errors. Short Open Tags =============== Always use full PHP opening tags, in case a server does not have -short_open_tag enabled. +*short_open_tag* enabled. **INCORRECT**:: @@ -606,6 +603,8 @@ short_open_tag enabled. <?php echo $foo; ?> +.. note:: PHP 5.4 will always have the **<?=** tag available. + One Statement Per Line ====================== @@ -645,7 +644,7 @@ characters. SQL Queries =========== -MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, +SQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc. Break up long queries into multiple lines for legibility, preferably @@ -674,5 +673,4 @@ Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and provides common fallback values which can save a few lines of code. Example:: - function foo($bar = '', $baz = FALSE) - + function foo($bar = '', $baz = FALSE)
\ No newline at end of file diff --git a/user_guide_src/source/general/urls.rst b/user_guide_src/source/general/urls.rst index 6b390b559..d678e4a0a 100644 --- a/user_guide_src/source/general/urls.rst +++ b/user_guide_src/source/general/urls.rst @@ -20,7 +20,6 @@ approach, usually represent:: example.com/class/function/ID - #. The first segment represents the controller **class** that should be invoked. #. The second segment represents the class **function**, or method, that @@ -28,9 +27,28 @@ approach, usually represent:: #. The third, and any additional segments, represent the ID and any variables that will be passed to the controller. -The :doc:`URI Class <../libraries/uri>` and the :doc:`URL Helper <../helpers/url_helper>` contain functions that make it -easy to work with your URI data. In addition, your URLs can be remapped -using the :doc:`URI Routing <routing>` feature for more flexibility. +The :doc:`URI Library <../libraries/uri>` and the :doc:`URL Helper +<../helpers/url_helper>` contain functions that make it easy to work +with your URI data. In addition, your URLs can be remapped using the +:doc:`URI Routing <routing>` feature for more flexibility. + +Friendly URLs +============= + +As you might guess, since there's a straight relationship between +URI segments and the controller/method pair that's being called, +those two determining segments must represent a valid class and +method name. +You may however also use dashes in the class/method-representing +segments, and they will automatically be translated to underscores +in order to be valid routed segments. + +For example:: + + example.com/my-settings/change-password/ + +The above example will route to the ``My_settings`` controller and +its method ``change_password()``. Removing the index.php file =========================== @@ -39,7 +57,7 @@ By default, the **index.php** file will be included in your URLs:: example.com/index.php/news/article/my_article -If your Apache server has mod_rewrite enabled, you can easily remove this +If your Apache server has *mod_rewrite* enabled, you can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the "negative" method in which everything is redirected except the specified items: @@ -54,7 +72,10 @@ except the specified items: In the above example, any HTTP request other than those for existing directories and existing files is treated as a request for your index.php file. -.. note:: Note: These specific rules might not work for all server configurations. +.. note:: These specific rules might not work for all server configurations. + +.. note:: Make sure to also exclude from the above rule any assets that you + might need to be accessible from the outside world. Adding a URL Suffix =================== @@ -91,7 +112,7 @@ active. Your controllers and functions will then be accessible using the index.php?c=controller&m=method -.. note:: If you are using query strings you will have to build - your own URLs, rather than utilizing the URL helpers (and other helpers - that generate URLs, like some of the form helpers) as these are designed - to work with segment based URLs. +.. note:: If you are using query strings you will have to build your own + URLs, rather than utilizing the URL helpers (and other helpers + that generate URLs, like some of the form helpers) as these are + designed to work with segment based URLs.
\ No newline at end of file diff --git a/user_guide_src/source/general/views.rst b/user_guide_src/source/general/views.rst index 9b7c9daaa..4b1ab3c34 100644 --- a/user_guide_src/source/general/views.rst +++ b/user_guide_src/source/general/views.rst @@ -31,20 +31,22 @@ in it:: </body> </html> -Then save the file in your application/views/ folder. +Then save the file in your *application/views/* directory. Loading a View ============== -To load a particular view file you will use the following function:: +To load a particular view file you will use the following method:: $this->load->view('name'); -Where name is the name of your view file. Note: The .php file extension -does not need to be specified unless you use something other than .php. +Where name is the name of your view file. + +.. note:: The .php file extension does not need to be specified + unless you use something other than .php. Now, open the controller file you made earlier called blog.php, and -replace the echo statement with the view loading function:: +replace the echo statement with the view loading method:: <?php class Blog extends CI_Controller { @@ -54,7 +56,6 @@ replace the echo statement with the view loading function:: $this->load->view('blogview'); } } - ?> If you visit your site using the URL you did earlier you should see your new view. The URL was similar to this:: @@ -65,7 +66,7 @@ Loading multiple views ====================== CodeIgniter will intelligently handle multiple calls to -$this->load->view from within a controller. If more than one call +``$this->load->view()`` from within a controller. If more than one call happens they will be appended together. For example, you may wish to have a header view, a menu view, a content view, and a footer view. That might look something like this:: @@ -84,32 +85,31 @@ might look something like this:: } } - ?> In the example above, we are using "dynamically added data", which you will see below. -Storing Views within Sub-folders -================================ +Storing Views within Sub-directories +==================================== -Your view files can also be stored within sub-folders if you prefer that -type of organization. When doing so you will need to include the folder -name loading the view. Example:: +Your view files can also be stored within sub-directories if you prefer +that type of organization. When doing so you will need to include the +directory name loading the view. Example:: - $this->load->view('folder_name/file_name'); + $this->load->view('directory_name/file_name'); Adding Dynamic Data to the View =============================== Data is passed from the controller to the view by way of an **array** or -an **object** in the second parameter of the view loading function. Here +an **object** in the second parameter of the view loading method. Here is an example using an array:: $data = array( - 'title' => 'My Title', - 'heading' => 'My Heading', - 'message' => 'My Message' - ); + 'title' => 'My Title', + 'heading' => 'My Heading', + 'message' => 'My Message' + ); $this->load->view('blogview', $data); @@ -118,8 +118,8 @@ And here's an example using an object:: $data = new Someclass(); $this->load->view('blogview', $data); -Note: If you use an object, the class variables will be turned into -array elements. +.. note:: If you use an object, the class variables will be turned + into array elements. Let's try it with your controller file. Open it add this code:: @@ -134,7 +134,6 @@ Let's try it with your controller file. Open it add this code:: $this->load->view('blogview', $data); } } - ?> Now open your view file and change the text to variables that correspond to the array keys in your data:: @@ -174,7 +173,6 @@ Here's a simple example. Add this to your controller:: $this->load->view('blogview', $data); } } - ?> Now open your view file and create a loop:: @@ -200,17 +198,16 @@ Now open your view file and create a loop:: .. note:: You'll notice that in the example above we are using PHP's alternative syntax. If you are not familiar with it you can read about - it :doc:`here </general/alternative_php>`. + it :doc:`here <alternative_php>`. Returning views as data ======================= There is a third **optional** parameter lets you change the behavior of -the function so that it returns data as a string rather than sending it +the method so that it returns data as a string rather than sending it to your browser. This can be useful if you want to process the data in -some way. If you set the parameter to true (boolean) it will return +some way. If you set the parameter to TRUE (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it to a variable if you want the data returned:: - $string = $this->load->view('myfile', '', true); - + $string = $this->load->view('myfile', '', TRUE);
\ No newline at end of file diff --git a/user_guide_src/source/general/welcome.rst b/user_guide_src/source/general/welcome.rst index b28c3bcc2..b6f473c2b 100644 --- a/user_guide_src/source/general/welcome.rst +++ b/user_guide_src/source/general/welcome.rst @@ -29,4 +29,4 @@ CodeIgniter is right for you if: - You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one). - You eschew complexity, favoring simple solutions. -- You need clear, thorough documentation. +- You need clear, thorough documentation.
\ No newline at end of file diff --git a/user_guide_src/source/helpers/array_helper.rst b/user_guide_src/source/helpers/array_helper.rst index 15b5e17c4..9435b3ac7 100644 --- a/user_guide_src/source/helpers/array_helper.rst +++ b/user_guide_src/source/helpers/array_helper.rst @@ -10,9 +10,7 @@ arrays. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('array'); @@ -21,20 +19,19 @@ The following functions are available: element() ========= -.. php:method:: element($item, $array, $default = NULL) - - :param string $item: Item to fetch from the array - :param array $array: Input array - :param boolean $default: What to return if the array isn't valid - :returns: NULL on failure or the array item. +.. php:function:: element($item, $array, $default = NULL) + :param string $item: Item to fetch from the array + :param array $array: Input array + :param bool $default: What to return if the array isn't valid + :returns: NULL on failure or the array item. Lets you fetch an item from an array. The function tests whether the array index is set and whether it has a value. If a value exists it is returned. If a value does not exist it returns NULL, or whatever you've -specified as the default value via the third parameter. Example +specified as the default value via the third parameter. -:: +Example:: $array = array( 'color' => 'red', @@ -48,21 +45,19 @@ specified as the default value via the third parameter. Example elements() ========== +.. php:function:: elements($items, $array, $default = NULL) + + :param string $item: Item to fetch from the array + :param array $array: Input array + :param bool $default: What to return if the array isn't valid + :returns: NULL on failure or the array item. + Lets you fetch a number of items from an array. The function tests whether each of the array indices is set. If an index does not exist it is set to NULL, or whatever you've specified as the default value via the third parameter. -.. php:method:: elements($items, $array, $default = NULL) - - :param string $item: Item to fetch from the array - :param array $array: Input array - :param boolean $default: What to return if the array isn't valid - :returns: NULL on failure or the array item. - -Example - -:: +Example:: $array = array( 'color' => 'red', @@ -73,9 +68,7 @@ Example $my_shape = elements(array('color', 'shape', 'height'), $array); -The above will return the following array - -:: +The above will return the following array:: array( 'color' => 'red', @@ -83,15 +76,12 @@ The above will return the following array 'height' => NULL ); -You can set the third parameter to any default value you like - +You can set the third parameter to any default value you like. :: $my_shape = elements(array('color', 'shape', 'height'), $array, 'foobar'); -The above will return the following array - -:: +The above will return the following array:: array( 'color' => 'red', @@ -99,9 +89,9 @@ The above will return the following array 'height' => 'foobar' ); -This is useful when sending the $_POST array to one of your Models. +This is useful when sending the ``$_POST`` array to one of your Models. This prevents users from sending additional POST data to be entered into -your tables +your tables. :: @@ -116,15 +106,14 @@ updated. random_element() ================ -Takes an array as input and returns a random element from it. Usage -example +.. php:function:: random_element($array) -.. php:method:: random_element($array) + :param array $array: Input array + :returns: string (a random element from the array) - :param array $array: Input array - :returns: String - Random element from the array. +Takes an array as input and returns a random element from it. -:: +Usage example:: $quotes = array( "I find that the harder I work, the more luck I seem to have. - Thomas Jefferson", @@ -135,5 +124,4 @@ example "Chance favors the prepared mind - Louis Pasteur" ); - echo random_element($quotes); - + echo random_element($quotes);
\ No newline at end of file diff --git a/user_guide_src/source/helpers/captcha_helper.rst b/user_guide_src/source/helpers/captcha_helper.rst index 90244739b..17462a8de 100644 --- a/user_guide_src/source/helpers/captcha_helper.rst +++ b/user_guide_src/source/helpers/captcha_helper.rst @@ -11,78 +11,72 @@ Loading this Helper =================== This helper is loaded using the following code - :: $this->load->helper('captcha'); The following functions are available: -create_captcha($data) -===================== +create_captcha() +================ + +.. php:function:: function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '') + + :param array $data: Array of data for the CAPTCHA + :param string $img_path: Path to create the image in + :param string $img_url: URL to the CAPTCHA image folder + :param string $font_path: Server path to font + :returns: array('word' => $word, 'time' => $now, 'image' => $img) Takes an array of information to generate the CAPTCHA as input and creates the image to your specifications, returning an array of associative data about the image. -.. php:method:: function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '') - - :param array $data: array of data for the CAPTCHA - :param string $img_path: path to create the image in - :param string $img_url: URL to the CAPTCHA image folder - :param string $font_path: server path to font - :returns: array('word' => $word, 'time' => $now, 'image' => $img) - - :: - [array] ( - 'image' => IMAGE TAG - 'time' => TIMESTAMP (in microtime) - 'word' => CAPTCHA WORD ) + array( + 'image' => IMAGE TAG + 'time' => TIMESTAMP (in microtime) + 'word' => CAPTCHA WORD + ) -The "image" is the actual image tag: - -:: +The **image** is the actual image tag:: <img src="http://example.com/captcha/12345.jpg" width="140" height="50" /> - -The "time" is the micro timestamp used as the image name without the +The **time** is the micro timestamp used as the image name without the file extension. It will be a number like this: 1139612155.3422 -The "word" is the word that appears in the captcha image, which if not +The **word** is the word that appears in the captcha image, which if not supplied to the function, will be a random string. Using the CAPTCHA helper ------------------------ -Once loaded you can generate a captcha like this - -:: +Once loaded you can generate a captcha like this:: - $vals = array( - 'word' => 'Random word', - 'img_path' => './captcha/', - 'img_url' => 'http://example.com/captcha/', - 'font_path' => './path/to/fonts/texb.ttf', - 'img_width' => '150', - 'img_height' => 30, - 'expiration' => 7200 + $vals = array( + 'word' => 'Random word', + 'img_path' => './captcha/', + 'img_url' => 'http://example.com/captcha/', + 'font_path' => './path/to/fonts/texb.ttf', + 'img_width' => '150', + 'img_height' => 30, + 'expiration' => 7200 ); - $cap = create_captcha($vals); echo $cap['image']; - + $cap = create_captcha($vals); + echo $cap['image']; - The captcha function requires the GD image library. -- Only the img_path and img_url are required. -- If a "word" is not supplied, the function will generate a random +- Only the **img_path** and **img_url** are required. +- If a **word** is not supplied, the function will generate a random ASCII string. You might put together your own word library that you can draw randomly from. - If you do not specify a path to a TRUE TYPE font, the native ugly GD font will be used. - The "captcha" folder must be writable (666, or 777) -- The "expiration" (in seconds) signifies how long an image will remain +- The **expiration** (in seconds) signifies how long an image will remain in the captcha folder before it will be deleted. The default is two hours. @@ -90,14 +84,12 @@ Adding a Database ----------------- In order for the captcha function to prevent someone from submitting, -you will need to add the information returned from create_captcha() -function to your database. Then, when the data from the form is -submitted by the user you will need to verify that the data exists in -the database and has not expired. +you will need to add the information returned from ``create_captcha()`` +to your database. Then, when the data from the form is submitted by +the user you will need to verify that the data exists in the database +and has not expired. -Here is a table prototype - -:: +Here is a table prototype:: CREATE TABLE captcha ( captcha_id bigint(13) unsigned NOT NULL auto_increment, @@ -109,9 +101,7 @@ Here is a table prototype ); Here is an example of usage with a database. On the page where the -CAPTCHA will be shown you'll have something like this - -:: +CAPTCHA will be shown you'll have something like this:: $this->load->helper('captcha'); $vals = array( @@ -134,23 +124,20 @@ CAPTCHA will be shown you'll have something like this echo '<input type="text" name="captcha" value="" />'; Then, on the page that accepts the submission you'll have something like -this - -:: +this:: // First, delete old captchas $expiration = time() - 7200; // Two hour limit $this->db->where('captcha_time < ', $expiration) - ->delete('captcha'); + ->delete('captcha'); // Then see if a captcha exists: - $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?"; + $sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?'; $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration); $query = $this->db->query($sql, $binds); $row = $query->row(); if ($row->count == 0) { - echo "You must submit the word that appears in the image"; - } - + echo 'You must submit the word that appears in the image.'; + }
\ No newline at end of file diff --git a/user_guide_src/source/helpers/cookie_helper.rst b/user_guide_src/source/helpers/cookie_helper.rst index 30e601c32..c41193c3c 100644 --- a/user_guide_src/source/helpers/cookie_helper.rst +++ b/user_guide_src/source/helpers/cookie_helper.rst @@ -10,9 +10,7 @@ cookies. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('cookie'); @@ -21,52 +19,53 @@ The following functions are available: set_cookie() ============ +.. php:function:: set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) + + :param string $name: Cookie name + :param string $value: Cookie value + :param int $expire: Number of seconds until expiration + :param string $domain: Cookie domain (usually: .yourdomain.com) + :param string $path: Cookie path + :param string $prefix: Cookie name prefix + :param bool $secure: Whether to only send the cookie through HTTPS + :param bool $httponly: Whether to hide the cookie from JavaScript + :returns: void + This helper function gives you view file friendly syntax to set browser -cookies. Refer to the :doc:`Input class <../libraries/input>` for a -description of use, as this function is an alias to -`$this->input->set_cookie()`. - -.. php:method:: set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE) - - :param string $name: the name of the cookie - :param string $value: the value of the cookie - :param string $expire: the number of seconds until expiration - :param string $domain: the cookie domain. Usually: .yourdomain.com - :param string $path: the cookie path - :param string $prefix: the cookie prefix - :param boolean $secure: secure cookie or not. - :returns: void +cookies. Refer to the :doc:`Input Library <../libraries/input>` for a +description of its use, as this function is an alias for +``CI_Input::set_cookie()``. get_cookie() ============ -This helper function gives you view file friendly syntax to get browser -cookies. Refer to the :doc:`Input class <../libraries/input>` for a -description of use, as this function is an alias to `$this->input->cookie()`. +.. php:function:: get_cookie($index = '', $xss_clean = FALSE) -.. php:method:: get_cookie($index = '', $xss_clean = FALSE) + :param string $index: Cookie name + :param bool $xss_clean: Whether to apply XSS filtering to the returned value + :returns: mixed - :param string $index: the name of the cookie - :param boolean $xss_clean: If the resulting value should be xss_cleaned or not - :returns: mixed +This helper function gives you view file friendly syntax to get browser +cookies. Refer to the :doc:`Input Library <../libraries/input>` for a +description of itsuse, as this function is an alias for ``CI_Input::cookie()``. delete_cookie() =============== -Lets you delete a cookie. Unless you've set a custom path or other -values, only the name of the cookie is needed - -.. php:method:: delete_cookie($name = '', $domain = '', $path = '/', $prefix = '') +.. php:function:: delete_cookie($name = '', $domain = '', $path = '/', $prefix = '') - :param string $name: the name of the cookie - :param string $domain: cookie domain (ususally .example.com) - :param string $path: cookie path - :param string $prefix: cookie prefix + :param string $name: Cookie name + :param string $domain: Cookie domain (usually: .yourdomain.com) + :param string $path: Cookie path + :param string $prefix: Cookie name prefix :returns: void +Lets you delete a cookie. Unless you've set a custom path or other +values, only the name of the cookie is needed. + :: - delete_cookie("name"); + delete_cookie('name'); This function is otherwise identical to ``set_cookie()``, except that it does not have the value and expiration parameters. You can submit an diff --git a/user_guide_src/source/helpers/date_helper.rst b/user_guide_src/source/helpers/date_helper.rst index 9de925ba7..3a3454edc 100644 --- a/user_guide_src/source/helpers/date_helper.rst +++ b/user_guide_src/source/helpers/date_helper.rst @@ -9,9 +9,7 @@ The Date Helper file contains functions that help you work with dates. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('date'); @@ -20,44 +18,45 @@ The following functions are available: now() ===== -Returns the current time as a Unix timestamp, referenced either to your -server's local time or any PHP suported timezone, based on the "time reference" -setting in your config file. If you do not intend to set your master time reference -to any other PHP suported timezone (which you'll typically do if you run a site that -lets each user set their own timezone settings) there is no benefit to using this -function over PHP's time() function. +.. php:function:: now($timezone = NULL) -.. php:method:: now($timezone = NULL) + :param string $timezone: Timezone + :returns: int - :param string $timezone: The timezone you want to be returned - :returns: integer +Returns the current time as a UNIX timestamp, referenced either to your server's +local time or any PHP suported timezone, based on the "time reference" setting +in your config file. If you do not intend to set your master time reference to +any other PHP supported timezone (which you'll typically do if you run a site +that lets each user set their own timezone settings) there is no benefit to using +this function over PHP's ``time()`` function. :: - echo now("Australia/Victoria"); -If a timezone is not provided, it will return time() based on "time_reference" setting. + echo now('Australia/Victoria'); + +If a timezone is not provided, it will return ``time()`` based on the +**time_reference** setting. mdate() ======= +.. php:function:: mdate($datestr = '', $time = '') + + :param string $datestr: Date string + :param int $time: UNIX timestamp + :returns: int + This function is identical to PHP's `date() <http://www.php.net/date>`_ function, except that it lets you use MySQL style date codes, where each -code letter is preceded with a percent sign: %Y %m %d etc. +code letter is preceded with a percent sign, e.g. `%Y %m %d` The benefit of doing dates this way is that you don't have to worry about escaping any characters that are not date codes, as you would -normally have to do with the date() function. Example - -.. php:method:: mdate($datestr = '', $time = '') +normally have to do with the ``date()`` function. - :param string $datestr: Date String - :param integer $time: time - :returns: integer +Example:: - -:: - - $datestring = "Year: %Y Month: %m Day: %d - %h:%i %a"; + $datestring = 'Year: %Y Month: %m Day: %d - %h:%i %a'; $time = time(); echo mdate($datestring, $time); @@ -67,32 +66,30 @@ will be used. standard_date() =============== -Lets you generate a date string in one of several standardized formats. -Example +.. php:function:: standard_date($fmt = 'DATE_RFC822', $time = NULL) -.. php:method:: standard_date($fmt = 'DATE_RFC822', $time = '') + :param string $fmt: Date format + :param int $time: UNIX timestamp + :returns: string - :param string $fmt: the chosen format - :param string $time: Unix timestamp - :returns: string +Lets you generate a date string in one of several standardized formats. -:: +Example:: $format = 'DATE_RFC822'; $time = time(); echo standard_date($format, $time); -The first parameter must contain the format, the second parameter must -contain the date as a Unix timestamp. - -.. note:: This function is DEPRECATED. Use the native ``date()`` combined - with `DateTime's format constants <http://www.php.net/manual/en/class.datetime.php#datetime.constants.types>`_ +.. note:: This function is DEPRECATED.Use the native ``date()`` combined with + `DateTime's format constants + <http://www.php.net/manual/en/class.datetime.php#datetime.constants.types>`_ instead: | | echo date(DATE_RFC822, time()); -Supported formats: +Supported formats +----------------- =============== ======================= ====================================== Constant Description Example @@ -112,39 +109,34 @@ DATE_W3C W3C 2005-08-14T16:13:03+0000 local_to_gmt() ============== -Takes a Unix timestamp as input and returns it as GMT. +.. php:function:: local_to_gmt($time = '') -.. php:method:: local_to_gmt($time = '') + :param int $time: UNIX timestamp + :returns: string - :param integer $time: Unix timestamp - :returns: string +Takes a UNIX timestamp as input and returns it as GMT. -Example: +Example:: -:: - - $now = time(); - $gmt = local_to_gmt($now); + $gmt = local_to_gmt(time()); gmt_to_local() ============== -Takes a Unix timestamp (referenced to GMT) as input, and converts it to -a localized timestamp based on the timezone and Daylight Saving time -submitted. - -.. php:method:: gmt_to_local($time = '', $timezone = 'UTC', $dst = FALSE) +.. php:function:: gmt_to_local($time = '', $timezone = 'UTC', $dst = FALSE) - :param integer $time: Unix timestamp - :param string $timezone: timezone - :param boolean $dst: whether DST is active - :returns: integer + :param int $time: UNIX timestamp + :param string $timezone: Timezone + :param bool $dst: Whether DST is active + :returns: int -Example +Takes a UNIX timestamp (referenced to GMT) as input, and converts it to +a localized timestamp based on the timezone and Daylight Saving Time +submitted. -:: +Example:: - $timestamp = '1140153693'; + $timestamp = 1140153693; $timezone = 'UM8'; $daylight_saving = TRUE; echo gmt_to_local($timestamp, $timezone, $daylight_saving); @@ -152,40 +144,32 @@ Example .. note:: For a list of timezones see the reference at the bottom of this page. - mysql_to_unix() =============== -Takes a MySQL Timestamp as input and returns it as Unix. +.. php:function:: mysql_to_unix($time = '') -.. php:method:: mysql_to_unix($time = '') + :param int $time: UNIX timestamp + :returns: int - :param integer $time: Unix timestamp - :returns: integer - -Example +Takes a MySQL Timestamp as input and returns it as a UNIX timestamp. -:: +Example:: - $mysql = '20061124092345'; - $unix = mysql_to_unix($mysql); + $unix = mysql_to_unix('20061124092345'); unix_to_human() =============== -Takes a Unix timestamp as input and returns it in a human readable -format with this prototype +.. php:function:: unix_to_human($time = '', $seconds = FALSE, $fmt = 'us') -.. php:method:: unix_to_human($time = '', $seconds = FALSE, $fmt = 'us') - - :param integer $time: Unix timestamp - :param boolean $seconds: whether to show seconds - :param string $fmt: format: us or euro + :param int $time: UNIX timestamp + :param bool $seconds: Whether to show seconds + :param string $fmt: format (us or euro) :returns: integer -Example - -:: +Takes a UNIX timestamp as input and returns it in a human readable +format with this prototype:: YYYY-MM-DD HH:MM:SS AM/PM @@ -194,9 +178,9 @@ submission. The time can be formatted with or without seconds, and it can be set to European or US format. If only the timestamp is submitted it will return -the time without seconds formatted for the U.S. Examples +the time without seconds formatted for the U.S. -:: +Examples:: $now = time(); echo unix_to_human($now); // U.S. time, no seconds @@ -206,19 +190,17 @@ the time without seconds formatted for the U.S. Examples human_to_unix() =============== -The opposite of the above function. Takes a "human" time as input and -returns it as Unix. This function is useful if you accept "human" -formatted dates submitted via a form. Returns FALSE (boolean) if the -date string passed to it is not formatted as indicated above. +.. php:function:: human_to_unix($datestr = '') -.. php:method:: human_to_unix($datestr = '') - - :param integer $datestr: Date String - :returns: integer + :param int $datestr: Date string + :returns: int UNIX timestamp or FALSE on failure -Example: +The opposite of the :php:func:`unix_to_time()` function. Takes a "human" +time as input and returns it as a UNIX timestamp. This is useful if you +accept "human" formatted dates submitted via a form. Returns boolean FALSE +date string passed to it is not formatted as indicated above. -:: +Example:: $now = time(); $human = unix_to_human($now); @@ -227,22 +209,20 @@ Example: nice_date() =========== -This function can take a number poorly-formed date formats and convert -them into something useful. It also accepts well-formed dates. - -The function will return a Unix timestamp by default. You can, -optionally, pass a format string (the same type as the PHP date function -accepts) as the second parameter. +.. php:function:: nice_date($bad_date = '', $format = FALSE) -.. php:method:: nice_date($bad_date = '', $format = FALSE) + :param int $bad_date: The terribly formatted date-like string + :param string $format: Date format to return (same as PHP's ``date()`` function) + :returns: string - :param integer $bad_date: The terribly formatted date-like string - :param string $format: Date format to return (same as php date function) - :returns: string +This function can take a number poorly-formed date formats and convert +them into something useful. It also accepts well-formed dates. -Example +The function will return a UNIX timestamp by default. You can, optionally, +pass a format string (the same type as the PHP ``date()`` function accepts) +as the second parameter. -:: +Example:: $bad_date = '199605'; // Should Produce: 1996-05-01 @@ -255,28 +235,28 @@ Example timespan() ========== -Formats a unix timestamp so that is appears similar to this -:: +.. php:function:: timespan($seconds = 1, $time = '', $units = '') - 1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes + :param int $seconds: Number of seconds + :param string $time: UNIX timestamp + :param int $units: Number of time units to display + :returns: string -The first parameter must contain a Unix timestamp. The second parameter -must contain a timestamp that is greater that the first timestamp. If -the second parameter empty, the current time will be used. The third -parameter is optional and limits the number of time units to display. -The most common purpose for this function is to show how much time has -elapsed from some point in time in the past to now. +Formats a UNIX timestamp so that is appears similar to this:: -.. php:method:: timespan($seconds = 1, $time = '', $units = '') + 1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes - :param integer $seconds: a number of seconds - :param string $time: Unix timestamp - :param integer $units: a number of time units to display - :returns: string +The first parameter must contain a UNIX timestamp. +The second parameter must contain a timestamp that is greater that the +first timestamp. +The thirdparameter is optional and limits the number of time units to display. -Example +If the second parameter empty, the current time will be used. -:: +The most common purpose for this function is to show how much time has +elapsed from some point in time in the past to now. + +Example:: $post_date = '1079621429'; $now = time(); @@ -284,23 +264,21 @@ Example echo timespan($post_date, $now, $units); .. note:: The text generated by this function is found in the following language - file: language/<your_lang>/date_lang.php + file: `language/<your_lang>/date_lang.php` days_in_month() =============== -Returns the number of days in a given month/year. Takes leap years into -account. +.. php:function:: days_in_month($month = 0, $year = '') -.. php:method:: days_in_month($month = 0, $year = '') + :param int $month: a numeric month + :param int $year: a numeric year + :returns: int - :param integer $month: a numeric month - :param integer $year: a numeric year - :returns: integer - -Example +Returns the number of days in a given month/year. Takes leap years into +account. -:: +Example:: echo days_in_month(06, 2005); @@ -309,19 +287,17 @@ If the second parameter is empty, the current year will be used. date_range() ============ -Returns a list of dates within a specified period. - -.. php:method:: date_range($unix_start = '', $mixed = '', $is_unix = TRUE, $format = 'Y-m-d') +.. php:function:: date_range($unix_start = '', $mixed = '', $is_unix = TRUE, $format = 'Y-m-d') - :param integer $unix_start: UNIX timestamp of the range start date - :param integer $mixed: UNIX timestamp of the range end date or interval in days - :param boolean $is_unix: set to FALSE if $mixed is not a timestamp - :param string $format: output date format, same as in date() - :returns: array + :param int $unix_start: UNIX timestamp of the range start date + :param int $mixed: UNIX timestamp of the range end date or interval in days + :param bool $is_unix: set to FALSE if $mixed is not a timestamp + :param string $format: Output date format, same as in ``date()`` + :returns: array -Example +Returns a list of dates within a specified period. -:: +Example:: $range = date_range('2012-01-01', '2012-01-15'); echo "First 15 days of 2012:"; @@ -333,29 +309,34 @@ Example timezones() =========== +.. php:function:: timezones($tz = '') + + :param string $tz: a numeric timezone + :returns: string + Takes a timezone reference (for a list of valid timezones, see the "Timezone Reference" below) and returns the number of hours offset from UTC. -.. php:method:: timezones($tz = '') - - :param string $tz: a numeric timezone - :returns: string - -Example - -:: +Example:: echo timezones('UM5'); -This function is useful when used with `timezone_menu()`. +This function is useful when used with :php:func:`timezone_menu()`. timezone_menu() =============== -Generates a pull-down menu of timezones, like this one: +.. php:function:: timezone_menu($default = 'UTC', $class = '', $name = 'timezones', $attributes = '') + :param string $default: Timezone + :param string $class: Class name + :param string $name: Menu name + :param mixed $attributes: HTML attributes + :returns: string + +Generates a pull-down menu of timezones, like this one: .. raw:: html @@ -409,19 +390,7 @@ This menu is useful if you run a membership site in which your users are allowed to set their local timezone value. The first parameter lets you set the "selected" state of the menu. For -example, to set Pacific time as the default you will do this - -.. php:method:: timezone_menu($default = 'UTC', $class = '', $name = 'timezones', $attributes = '') - - :param string $default: timezone - :param string $class: classname - :param string $name: menu name - :param mixed $attributes: attributes - :returns: string - -Example: - -:: +example, to set Pacific time as the default you will do this:: echo timezone_menu('UM8'); @@ -445,37 +414,37 @@ Note some of the location lists have been abridged for clarity and formatting. =========== ===================================================================== Time Zone Location =========== ===================================================================== -UM2 (UTC - 12:00) Baker/Howland Island -UM1 (UTC - 11:00) Samoa Time Zone, Niue -UM0 (UTC - 10:00) Hawaii-Aleutian Standard Time, Cook Islands +UM2 (UTC - 12:00) Baker/Howland Island +UM1 (UTC - 11:00) Samoa Time Zone, Niue +UM0 (UTC - 10:00) Hawaii-Aleutian Standard Time, Cook Islands UM95 (UTC - 09:30) Marquesas Islands -UM9 (UTC - 09:00) Alaska Standard Time, Gambier Islands -UM8 (UTC - 08:00) Pacific Standard Time, Clipperton Island -UM7 (UTC - 11:00) Mountain Standard Time -UM6 (UTC - 06:00) Central Standard Time -UM5 (UTC - 05:00) Eastern Standard Time, Western Caribbean +UM9 (UTC - 09:00) Alaska Standard Time, Gambier Islands +UM8 (UTC - 08:00) Pacific Standard Time, Clipperton Island +UM7 (UTC - 11:00) Mountain Standard Time +UM6 (UTC - 06:00) Central Standard Time +UM5 (UTC - 05:00) Eastern Standard Time, Western Caribbean UM45 (UTC - 04:30) Venezuelan Standard Time -UM4 (UTC - 04:00) Atlantic Standard Time, Eastern Caribbean +UM4 (UTC - 04:00) Atlantic Standard Time, Eastern Caribbean UM35 (UTC - 03:30) Newfoundland Standard Time -UM3 (UTC - 03:00) Argentina, Brazil, French Guiana, Uruguay -UM2 (UTC - 02:00) South Georgia/South Sandwich Islands -UM (UTC -1:00) Azores, Cape Verde Islands -UTC (UTC) Greenwich Mean Time, Western European Time -UP1 (UTC +1:00) Central European Time, West Africa Time -UP2 (UTC +2:00) Central Africa Time, Eastern European Time -UP3 (UTC +3:00) Moscow Time, East Africa Time +UM3 (UTC - 03:00) Argentina, Brazil, French Guiana, Uruguay +UM2 (UTC - 02:00) South Georgia/South Sandwich Islands +UM (UTC -1:00) Azores, Cape Verde Islands +UTC (UTC) Greenwich Mean Time, Western European Time +UP1 (UTC +1:00) Central European Time, West Africa Time +UP2 (UTC +2:00) Central Africa Time, Eastern European Time +UP3 (UTC +3:00) Moscow Time, East Africa Time UP35 (UTC +3:30) Iran Standard Time -UP4 (UTC +4:00) Azerbaijan Standard Time, Samara Time +UP4 (UTC +4:00) Azerbaijan Standard Time, Samara Time UP45 (UTC +4:30) Afghanistan -UP5 (UTC +5:00) Pakistan Standard Time, Yekaterinburg Time +UP5 (UTC +5:00) Pakistan Standard Time, Yekaterinburg Time UP55 (UTC +5:30) Indian Standard Time, Sri Lanka Time UP575 (UTC +5:45) Nepal Time -UP6 (UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time +UP6 (UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time UP65 (UTC +6:30) Cocos Islands, Myanmar -UP7 (UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam -UP8 (UTC +8:00) Australian Western Standard Time, Beijing Time +UP7 (UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam +UP8 (UTC +8:00) Australian Western Standard Time, Beijing Time UP875 (UTC +8:45) Australian Central Western Standard Time -UP9 (UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk +UP9 (UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk UP95 (UTC +9:30) Australian Central Standard Time UP10 (UTC +10:00) Australian Eastern Standard Time, Vladivostok Time UP105 (UTC +10:30) Lord Howe Island @@ -483,6 +452,6 @@ UP11 (UTC +11:00) Magadan Time, Solomon Islands, Vanuatu UP115 (UTC +11:30) Norfolk Island UP12 (UTC +12:00) Fiji, Gilbert Islands, Kamchatka, New Zealand UP1275 (UTC +12:45) Chatham Islands Standard Time -UP1 (UTC +13:00) Phoenix Islands Time, Tonga +UP1 (UTC +13:00) Phoenix Islands Time, Tonga UP14 (UTC +14:00) Line Islands =========== =====================================================================
\ No newline at end of file diff --git a/user_guide_src/source/helpers/directory_helper.rst b/user_guide_src/source/helpers/directory_helper.rst index cf88732d3..a785ebc8c 100644 --- a/user_guide_src/source/helpers/directory_helper.rst +++ b/user_guide_src/source/helpers/directory_helper.rst @@ -57,7 +57,7 @@ be numerically indexed. Here is an example of a typical array:: ( [0] => benchmark.html [1] => config.html - [database] => Array + ["database/"] => Array ( [0] => query_builder.html [1] => binds.html @@ -76,5 +76,4 @@ be numerically indexed. Here is an example of a typical array:: [7] => loader.html [8] => pagination.html [9] => uri.html - ) - + )
\ No newline at end of file diff --git a/user_guide_src/source/helpers/download_helper.rst b/user_guide_src/source/helpers/download_helper.rst index e6094dc6b..1e9ec21ea 100644 --- a/user_guide_src/source/helpers/download_helper.rst +++ b/user_guide_src/source/helpers/download_helper.rst @@ -9,34 +9,40 @@ The Download Helper lets you download data to your desktop. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('download'); The following functions are available: -force_download('filename', 'data') -================================== +force_download() +================ + +.. php:function:: force_download($filename = '', $data = '', $set_mime = FALSE) + + :param string $filename: Filename + :param string $data: File contents + :param bool $set_mime: Whether to try to send the actual MIME type + :returns: void Generates server headers which force data to be downloaded to your desktop. Useful with file downloads. The first parameter is the **name you want the downloaded file to be named**, the second parameter is the -file data. Example +file data. + +If you set the third parameter to boolean TRUE, then the actual file MIME type +(based on the filename extension) will be sent, so that if your browser has a +handler for that type - it can use it. -:: +Example:: $data = 'Here is some text!'; $name = 'mytext.txt'; force_download($name, $data); If you want to download an existing file from your server you'll need to -read the file into a string +read the file into a string:: -:: - - $data = file_get_contents("/path/to/photo.jpg"); // Read the file's contents + $data = file_get_contents('/path/to/photo.jpg'); // Read the file's contents $name = 'myphoto.jpg'; - force_download($name, $data); - + force_download($name, $data);
\ No newline at end of file diff --git a/user_guide_src/source/helpers/email_helper.rst b/user_guide_src/source/helpers/email_helper.rst index d4e94b1ed..10adf1d0e 100644 --- a/user_guide_src/source/helpers/email_helper.rst +++ b/user_guide_src/source/helpers/email_helper.rst @@ -8,6 +8,8 @@ Class <../libraries/email>`. .. contents:: Page Contents +.. important:: The Email helper is DEPRECATED. + Loading this Helper =================== @@ -15,21 +17,21 @@ This helper is loaded using the following code:: $this->load->helper('email'); - The following functions are available: -valid_email('email') -==================== +valid_email() +============= -Checks if an email is a correctly formatted email. Note that is doesn't -actually prove the email will recieve mail, simply that it is a validly -formed address. +.. php:function:: valid_email($email) -It returns TRUE/FALSE + :param string $email: Email address + :returns: bool -:: +Checks if the input is a correctly formatted e-mail address. Note that is +doesn't actually prove that the address will be able recieve mail, but +simply that it is a validly formed address. - $this->load->helper('email'); +Example:: if (valid_email('email@somesite.com')) { @@ -40,10 +42,26 @@ It returns TRUE/FALSE echo 'email is not valid'; } -send_email('recipient', 'subject', 'message') -============================================= +.. note:: All that this function does is to use PHP's native ``filter_var()``: + | + | (bool) filter_var($email, FILTER_VALIDATE_EMAIL); -Sends an email using PHP's native -`mail() <http://www.php.net/function.mail>`_ function. For a more robust -email solution, see CodeIgniter's :doc:`Email -Class <../libraries/email>`. +send_email() +============ + +.. php:function:: send_email($recipient, $subject, $message) + + :param string $recipient: E-mail address + :param string $subject: Mail subject + :param string $message: Message body + :returns: bool + +Sends an email using PHP's native `mail() <http://www.php.net/function.mail>`_ +function. + +.. note:: All that this function does is to use PHP's native ``mail``: + | + | mail($recipient, $subject, $message); + +For a more robust email solution, see CodeIgniter's :doc:`Email Library +<../libraries/email>`. diff --git a/user_guide_src/source/helpers/file_helper.rst b/user_guide_src/source/helpers/file_helper.rst index 60c5aa98c..194d4348f 100644 --- a/user_guide_src/source/helpers/file_helper.rst +++ b/user_guide_src/source/helpers/file_helper.rst @@ -9,20 +9,23 @@ The File Helper file contains functions that assist in working with files. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('file'); The following functions are available: -read_file('path') -================= +read_file() +=========== -Returns the data contained in the file specified in the path. Example +.. php:function:: read_file($file) -:: + :param string $file: File path + :returns: string or FALSE on failure + +Returns the data contained in the file specified in the path. + +Example:: $string = read_file('./path/to/file.php'); @@ -35,14 +38,24 @@ The path can be a relative or full server path. Returns FALSE (boolean) on failu .. note:: This function is DEPRECATED. Use the native ``file_get_contents()`` instead. -If your server is running an `open_basedir` restriction this function might not work if you are trying to access a file above the calling script. +.. important:: If your server is running an **open_basedir** restriction this + function might not work if you are trying to access a file above the + calling script. -write_file('path', $data) -========================= +write_file() +============ -Writes data to the file specified in the path. If the file does not exist the function will create it. Example +.. php:function:: write_file($path, $data, $mode = 'wb') -:: + :param string $path: File path + :param string $data: Data to write to file + :param string $mode: ``fopen()`` mode + :returns: bool + +Writes data to the file specified in the path. If the file does not exist then the +function will create it. + +Example:: $data = 'Some file data'; if ( ! write_file('./path/to/file.php', $data)) @@ -54,85 +67,150 @@ Writes data to the file specified in the path. If the file does not exist the fu echo 'File written!'; } -You can optionally set the write mode via the third parameter - -:: +You can optionally set the write mode via the third parameter:: write_file('./path/to/file.php', $data, 'r+'); -The default mode is wb. Please see the `PHP user guide <http://php.net/fopen>`_ for mode options. +The default mode is 'wb'. Please see the `PHP user guide <http://php.net/fopen>`_ +for mode options. -Note: In order for this function to write data to a file its file permissions must be set such that it is writable (666, 777, etc.). If the file does not already exist, the directory containing it must be writable. +.. note: In order for this function to write data to a file, its permissions must + be set such that it is writable (666, 777, etc.). If the file does not + already exist, the directory containing it must be writable. .. note:: The path is relative to your main site index.php file, NOT your controller or view files. CodeIgniter uses a front controller so paths are always relative to the main site index. -delete_files('path') -==================== +.. note:: This function acquires an exclusive lock on the file while writing to it. -Deletes ALL files contained in the supplied path. Example +delete_files() +============== -:: +.. php:function:: delete_files($path, $del_dir = FALSE, $htdocs = FALSE) + + :param string $path: Directory path + :param bool $del_dir: Whether to also delete directories + :param bool $htdocs: Whether to skip deleting .htaccess and index page files + :returns: bool + +Deletes ALL files contained in the supplied path. + +Example:: delete_files('./path/to/directory/'); -If the second parameter is set to true, any directories contained within the supplied root path will be deleted as well. Example +If the second parameter is set to TRUE, any directories contained within the supplied +root path will be deleted as well. -:: +Example:: delete_files('./path/to/directory/', TRUE); .. note:: The files must be writable or owned by the system in order to be deleted. -get_filenames('path/to/directory/') -=================================== +get_filenames() +=============== + +.. php:function:: get_filenames($source_dir, $include_path = FALSE) + + :param string $source_dir: Directory path + :param bool $include_path: Whether to include the path as part of the filenames + :returns: array -Takes a server path as input and returns an array containing the names of all files contained within it. The file path can optionally be added to the file names by setting the second parameter to TRUE. +Takes a server path as input and returns an array containing the names of all files +contained within it. The file path can optionally be added to the file names by setting +the second parameter to TRUE. -get_dir_file_info('path/to/directory/', $top_level_only = TRUE) -=============================================================== +Example:: -Reads the specified directory and builds an array containing the filenames, filesize, dates, and permissions. Sub-folders contained within the specified path are only read if forced by sending the second parameter, $top_level_only to FALSE, as this can be an intensive operation. + $controllers = get_filenames(APPPATH.'controllers/'); -get_file_info('path/to/file', $file_information) -================================================ +get_dir_file_info() +=================== + +.. php:function:: get_dir_file_info($source_dir, $top_level_only) + + :param string $source_dir: Directory path + :param bool $top_level_only: Whether to look only at the specified directory + (excluding sub-directories) + :returns: array + +Reads the specified directory and builds an array containing the filenames, filesize, +dates, and permissions. Sub-folders contained within the specified path are only read +if forced by sending the second parameter to FALSE, as this can be an intensive +operation. + +Example:: + + $models_info = get_dir_file_info(APPPATH.'models/'); + +get_file_info() +=============== + +.. php:function: get_file_info($file, $returned_values = array('name', 'server_path', 'size', 'date')) + + :param string $file: File path + :param array $returned_values: What type of info to return + :returns: array or FALSE on failure -Given a file and path, returns the name, path, size, date modified. Second parameter allows you to explicitly declare what information you want returned; options are: `name`, `server_path`, `size`, `date`, `readable`, `writable`, `executable`, `fileperms`. Returns FALSE if the file cannot be found. +Given a file and path, returns (optionally) the *name*, *path*, *size* and *date modified* +information attributes for a file. Second parameter allows you to explicitly declare what +information you want returned. -.. note:: The "writable" uses the PHP function is_writable() which is known - to have issues on the IIS webserver. Consider using fileperms instead, - which returns information from PHP's fileperms() function. +Valid ``$returned_values`` options are: `name`, `size`, `date`, `readable`, `writeable`, +`executable` and `fileperms`. -get_mime_by_extension('file') -============================= +.. note:: The *writable* attribute is checked via PHP's ``is_writeable()`` function, which + known to have issues on the IIS webserver. Consider using *fileperms* instead, + which returns information from PHP's ``fileperms()`` function. -Translates a file extension into a mime type based on config/mimes.php. Returns FALSE if it can't determine the type, or open the mime config file. +get_mime_by_extension() +======================= + +.. php:function:: get_mime_by_extension($filename) + + :param string $filename: File name + :returns: string or FALSE on failure + +Translates a filename extension into a MIME type based on *config/mimes.php*. +Returns FALSE if it can't determine the type, or read the MIME config file. :: - $file = "somefile.png"; - echo $file . ' is has a mime type of ' . get_mime_by_extension($file); + $file = 'somefile.png'; + echo $file.' is has a mime type of '.get_mime_by_extension($file); + +.. note:: This is not an accurate way of determining file MIME types, and + is here strictly for convenience. It should not be used for security + purposes. +symbolic_permissions() +====================== -.. note:: This is not an accurate way of determining file mime types, and - is here strictly as a convenience. It should not be used for security. +.. php:function:: symbolic_permissions($perms) -symbolic_permissions($perms) -============================ + :param int $perms: Permissions + :returns: string -Takes numeric permissions (such as is returned by `fileperms()` and returns standard symbolic notation of file permissions. +Takes numeric permissions (such as is returned by ``fileperms()``) and returns +standard symbolic notation of file permissions. :: echo symbolic_permissions(fileperms('./index.php')); // -rw-r--r-- -octal_permissions($perms) -========================= +octal_permissions() +=================== -Takes numeric permissions (such as is returned by fileperms() and returns a three character octal notation of file permissions. +.. php:function:: octal_permissions($perms) -:: + :param int $perms: Permissions + :returns: string - echo octal_permissions(fileperms('./index.php')); // 644 +Takes numeric permissions (such as is returned by ``fileperms()``) and returns +a three character octal notation of file permissions. + +:: + echo octal_permissions(fileperms('./index.php')); // 644
\ No newline at end of file diff --git a/user_guide_src/source/helpers/form_helper.rst b/user_guide_src/source/helpers/form_helper.rst index 015bf1162..b2a9b6f0f 100644 --- a/user_guide_src/source/helpers/form_helper.rst +++ b/user_guide_src/source/helpers/form_helper.rst @@ -10,9 +10,7 @@ forms. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('form'); @@ -21,19 +19,27 @@ The following functions are available: form_open() =========== -Creates an opening form tag with a base URL **built from your config preferences**. It will optionally let you add form attributes and hidden input fields, and will always add the attribute accept-charset based on the charset value in your config file. +.. php:function:: form_open($action = '', $attributes = '', $hidden = array()) -The main benefit of using this tag rather than hard coding your own HTML is that it permits your site to be more portable in the event your URLs ever change. + :param string $action: Form action/target URI string + :param string $attributes: HTML attributes + :param array $hidden: An array of hidden fields' definitions + :returns: string -Here's a simple example +Creates an opening form tag with a base URL **built from your config preferences**. +It will optionally let you add form attributes and hidden input fields, and +will always add the `accept-charset` attribute based on the charset value in your +config file. -:: +The main benefit of using this tag rather than hard coding your own HTML is that +it permits your site to be more portable in the event your URLs ever change. - echo form_open('email/send'); +Here's a simple example:: -The above example would create a form that points to your base URL plus the "email/send" URI segments, like this + echo form_open('email/send'); -:: +The above example would create a form that points to your base URL plus the +"email/send" URI segments, like this:: <form method="post" accept-charset="utf-8" action="http://example.com/index.php/email/send" /> @@ -41,32 +47,25 @@ Adding Attributes ^^^^^^^^^^^^^^^^^ Attributes can be added by passing an associative array to the second -parameter, like this - -:: +parameter, like this:: $attributes = array('class' => 'email', 'id' => 'myform'); echo form_open('email/send', $attributes); -The above example would create a form similar to this - -:: +The above example would create a form similar to this:: <form method="post" accept-charset="utf-8" action="http://example.com/index.php/email/send" class="email" id="myform" /> Adding Hidden Input Fields ^^^^^^^^^^^^^^^^^^^^^^^^^^ -Hidden fields can be added by passing an associative array to the third parameter, like this +Hidden fields can be added by passing an associative array to the +third parameter, like this:: -:: - - $hidden = array('username' => 'Joe', 'member_id' => '234'); + $hidden = array('username' => 'Joe', 'member_id' => '234'); echo form_open('email/send', '', $hidden); -The above example would create a form similar to this - -:: +The above example would create a form similar to this:: <form method="post" accept-charset="utf-8" action="http://example.com/index.php/email/send"> <input type="hidden" name="username" value="Joe" /> @@ -75,29 +74,38 @@ The above example would create a form similar to this form_open_multipart() ===================== -This function is absolutely identical to the `form_open()` tag above -except that it adds a multipart attribute, which is necessary if you +.. php:function:: form_open_multipart($action = '', $attributes = array(), $hidden = array()) + + :param string $action: Form action/target URI string + :param string $attributes: HTML attributes + :param array $hidden: An array of hidden fields' definitions + :returns: string + +This function is absolutely identical to :php:func:`form_open()` above, +except that it adds a *multipart* attribute, which is necessary if you would like to use the form to upload files with. form_hidden() ============= -Lets you generate hidden input fields. You can either submit a -name/value string to create one field +.. php:function:: form_hidden($name, $value = '') -:: + :param string $name: Field name + :param string $value: Field value + :returns: string + +Lets you generate hidden input fields. You can either submit a +name/value string to create one field:: form_hidden('username', 'johndoe'); // Would produce: <input type="hidden" name="username" value="johndoe" /> -Or you can submit an associative array to create multiple fields - -:: +... or you can submit an associative array to create multiple fields:: $data = array( - 'name' => 'John Doe', - 'email' => 'john@example.com', - 'url' => 'http://example.com' + 'name' => 'John Doe', + 'email' => 'john@example.com', + 'url' => 'http://example.com' ); echo form_hidden($data); @@ -109,35 +117,32 @@ Or you can submit an associative array to create multiple fields <input type="hidden" name="url" value="http://example.com" /> */ -Or pass an associative array to the value field. - -:: +You can also pass an associative array to the value field:: $data = array( - 'name' => 'John Doe', - 'email' => 'john@example.com', - 'url' => 'http://example.com' + 'name' => 'John Doe', + 'email' => 'john@example.com', + 'url' => 'http://example.com' ); echo form_hidden('my_array', $data); /* Would produce: + <input type="hidden" name="my_array[name]" value="John Doe" /> <input type="hidden" name="my_array[email]" value="john@example.com" /> <input type="hidden" name="my_array[url]" value="http://example.com" /> */ -If you want to create hidden input fields with extra attributes - -:: +If you want to create hidden input fields with extra attributes:: $data = array( - 'type' => 'hidden', - 'name' => 'email', - 'id' => 'hiddenemail', - 'value' => 'john@example.com', - 'class' => 'hiddenemail' + 'type' => 'hidden', + 'name' => 'email', + 'id' => 'hiddenemail', + 'value' => 'john@example.com', + 'class' => 'hiddenemail' ); echo form_input($data); @@ -151,25 +156,28 @@ If you want to create hidden input fields with extra attributes form_input() ============ -Lets you generate a standard text input field. You can minimally pass -the field name and value in the first and second parameter +.. php:function:: form_input($data = '', $value = '', $extra = '') -:: + :param array $data: Field attributes data + :param string $value: Field value + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + +Lets you generate a standard text input field. You can minimally pass +the field name and value in the first and second parameter:: echo form_input('username', 'johndoe'); Or you can pass an associative array containing any data you wish your -form to contain - -:: +form to contain:: $data = array( - 'name' => 'username', - 'id' => 'username', - 'value' => 'johndoe', - 'maxlength' => '100', - 'size' => '50', - 'style' => 'width:50%' + 'name' => 'username', + 'id' => 'username', + 'value' => 'johndoe', + 'maxlength' => '100', + 'size' => '50', + 'style' => 'width:50%' ); echo form_input($data); @@ -181,9 +189,7 @@ form to contain */ If you would like your form to contain some additional data, like -Javascript, you can pass it as a string in the third parameter - -:: +JavaScript, you can pass it as a string in the third parameter:: $js = 'onClick="some_function()"'; echo form_input('username', 'johndoe', $js); @@ -191,34 +197,70 @@ Javascript, you can pass it as a string in the third parameter form_password() =============== -This function is identical in all respects to the `form_input()` function above except that it uses the "password" input type. +.. php:function:: form_password($data = '', $value = '', $extra = '') + + :param array $data: Field attributes data + :param string $value: Field value + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + +This function is identical in all respects to the :php:func:`form_input()` +function above except that it uses the "password" input type. form_upload() ============= -This function is identical in all respects to the `form_input()` function above except that it uses the "file" input type, allowing it to be used to upload files. +.. php:function:: form_upload($data = '', $value = '', $extra = '') + + :param array $data: Field attributes data + :param string $value: Field value + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + +This function is identical in all respects to the :php:func:`form_input()` +function above except that it uses the "file" input type, allowing it to +be used to upload files. form_textarea() =============== -This function is identical in all respects to the `form_input()` function above except that it generates a "textarea" type. Note: Instead of the "maxlength" and "size" attributes in the above example, you will instead specify "rows" and "cols". +.. php:function:: form_textarea($data = '', $value = '', $extra = '') + + :param array $data: Field attributes data + :param string $value: Field value + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + +This function is identical in all respects to the :php:func:`form_input()` +function above except that it generates a "textarea" type. + +.. note: Instead of the *maxlength* and *size* attributes in the above example, + you will instead specify *rows* and *cols*. form_dropdown() =============== +.. php:function:: form_dropdown($name = '', $options = array(), $selected = array(), $extra = '') + + :param string $name: Field name + :param array $options: An associative array of options to be listed + :param array $selected: List of fields to mark with the *selected* attribute + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + Lets you create a standard drop-down field. The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value you wish to be selected. You can also pass an array of multiple items through the third parameter, and CodeIgniter will create a -multiple select for you. Example +multiple select for you. -:: +Example:: $options = array( - 'small' => 'Small Shirt', - 'med' => 'Medium Shirt', - 'large' => 'Large Shirt', + 'small' => 'Small Shirt', + 'med' => 'Medium Shirt', + 'large' => 'Large Shirt', 'xlarge' => 'Extra Large Shirt', ); @@ -251,33 +293,47 @@ multiple select for you. Example If you would like the opening <select> to contain additional data, like an id attribute or JavaScript, you can pass it as a string in the fourth -parameter - -:: +parameter:: $js = 'id="shirts" onChange="some_function();"'; echo form_dropdown('shirts', $options, 'large', $js); -If the array passed as $options is a multidimensional array, -`form_dropdown()` will produce an <optgroup> with the array key as the +If the array passed as ``$options`` is a multidimensional array, then +``form_dropdown()`` will produce an <optgroup> with the array key as the label. form_multiselect() ================== +.. php:function:: form_multiselect($name = '', $options = array(), $selected = array(), $extra = '') + + :param string $name: Field name + :param array $options: An associative array of options to be listed + :param array $selected: List of fields to mark with the *selected* attribute + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + Lets you create a standard multiselect field. The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the -value or values you wish to be selected. The parameter usage is -identical to using form_dropdown() above, except of course that the -name of the field will need to use POST array syntax, e.g. foo[]. +value or values you wish to be selected. + +The parameter usage is identical to using :php:func:`form_dropdown()` above, +except of course that the name of the field will need to use POST array +syntax, e.g. foo[]. form_fieldset() -================ +=============== + +.. php:function:: form_fieldset($legend_text = '', $attributes = array()) + + :param string $legend_text: Text to put in the <legend> tag + :param array $attributes: Attributes to be set on the <fieldset> tag + :returns: string Lets you generate fieldset/legend fields. -:: +Example:: echo form_fieldset('Address Information'); echo "<p>fieldset content here</p>\n"; @@ -285,6 +341,7 @@ Lets you generate fieldset/legend fields. /* Produces: + <fieldset> <legend>Address Information</legend> <p>form content here</p> @@ -292,13 +349,11 @@ Lets you generate fieldset/legend fields. */ Similar to other functions, you can submit an associative array in the -second parameter if you prefer to set additional attributes. - -:: +second parameter if you prefer to set additional attributes:: $attributes = array( - 'id' => 'address_info', - 'class' => 'address_info' + 'id' => 'address_info', + 'class' => 'address_info' ); echo form_fieldset('Address Information', $attributes); @@ -317,22 +372,33 @@ second parameter if you prefer to set additional attributes. form_fieldset_close() ===================== +.. php:function:: form_fieldset_close($extra = '') + + :param string $extra: Anything to append after the closing tag, *as is* + :returns: string + Produces a closing </fieldset> tag. The only advantage to using this function is it permits you to pass data to it which will be added below the tag. For example :: - $string = "</div></div>"; + $string = '</div></div>'; echo form_fieldset_close($string); // Would produce: </fieldset></div></div> form_checkbox() =============== -Lets you generate a checkbox field. Simple example +.. php:function:: form_checkbox($data = '', $value = '', $checked = FALSE, $extra = '') -:: + :param array $data: Field attributes data + :param string $value: Field value + :param bool $checked: Whether to mark the checkbox as being *checked* + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + +Lets you generate a checkbox field. Simple example:: echo form_checkbox('newsletter', 'accept', TRUE); // Would produce: <input type="checkbox" name="newsletter" value="accept" checked="checked" /> @@ -346,21 +412,19 @@ array of attributes to the function :: $data = array( - 'name' => 'newsletter', - 'id' => 'newsletter', - 'value' => 'accept', - 'checked' => TRUE, - 'style' => 'margin:10px', + 'name' => 'newsletter', + 'id' => 'newsletter', + 'value' => 'accept', + 'checked' => TRUE, + 'style' => 'margin:10px' ); echo form_checkbox($data); // Would produce: <input type="checkbox" name="newsletter" id="newsletter" value="accept" checked="checked" style="margin:10px" /> -As with other functions, if you would like the tag to contain additional -data, like JavaScript, you can pass it as a string in the fourth -parameter - -:: +Also as with other functions, if you would like the tag to contain +additional data like JavaScript, you can pass it as a string in the +fourth parameter:: $js = 'onClick="some_function()"'; echo form_checkbox('newsletter', 'accept', TRUE, $js) @@ -368,29 +432,28 @@ parameter form_radio() ============ -This function is identical in all respects to the `form_checkbox()` -function above except that it uses the "radio" input type. - -form_submit() -============= +.. php:function:: form_radio($data = '', $value = '', $checked = FALSE, $extra = '') -Lets you generate a standard submit button. Simple example + :param array $data: Field attributes data + :param string $value: Field value + :param bool $checked: Whether to mark the radio button as being *checked* + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string -:: - - echo form_submit('mysubmit', 'Submit Post!'); - // Would produce: <input type="submit" name="mysubmit" value="Submit Post!" /> - -Similar to other functions, you can submit an associative array in the -first parameter if you prefer to set your own attributes. The third -parameter lets you add extra data to your form, like JavaScript. +This function is identical in all respects to the :php:func:`form_checkbox()` +function above except that it uses the "radio" input type. form_label() ============ -Lets you generate a <label>. Simple example +.. php:function:: form_label($label_text = '', $id = '', $attributes = array()) -:: + :param string $label_text: Text to put in the <label> tag + :param string $id: ID of the form element that we're making a label for + :param string $attributes: HTML attributes + :returns: string + +Lets you generate a <label>. Simple example:: echo form_label('What is your Name', 'username'); // Would produce: <label for="username">What is your Name</label> @@ -398,7 +461,7 @@ Lets you generate a <label>. Simple example Similar to other functions, you can submit an associative array in the third parameter if you prefer to set additional attributes. -:: +Example:: $attributes = array( 'class' => 'mycustomclass', @@ -408,87 +471,156 @@ third parameter if you prefer to set additional attributes. echo form_label('What is your Name', 'username', $attributes); // Would produce: <label for="username" class="mycustomclass" style="color: #000;">What is your Name</label> +form_submit() +============= + +.. php:function:: form_submit($data = '', $value = '', $extra = '') + + :param string $data: Button name + :param string $value: Button value + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + +Lets you generate a standard submit button. Simple example:: + + echo form_submit('mysubmit', 'Submit Post!'); + // Would produce: <input type="submit" name="mysubmit" value="Submit Post!" /> + +Similar to other functions, you can submit an associative array in the +first parameter if you prefer to set your own attributes. The third +parameter lets you add extra data to your form, like JavaScript. form_reset() ============ +.. php:function:: form_reset($data = '', $value = '', $extra = '') + + :param string $data: Button name + :param string $value: Button value + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string + Lets you generate a standard reset button. Use is identical to -`form_submit()`. +:php:func:`form_submit()`. form_button() ============= -Lets you generate a standard button element. You can minimally pass the -button name and content in the first and second parameter +.. php:function:: form_button($data = '', $content = '', $extra = '') -:: + :param string $data: Button name + :param string $content: Button label + :param string $extra: Extra attributes to be added to the tag *as is* + :returns: string - echo form_button('name','content'); - // Would produce <button name="name" type="button">Content</button> +Lets you generate a standard button element. You can minimally pass the +button name and content in the first and second parameter:: -Or you can pass an associative array containing any data you wish your -form to contain: + echo form_button('name','content'); + // Would produce: <button name="name" type="button">Content</button> -:: +Or you can pass an associative array containing any data you wish your +form to contain:: $data = array( - 'name' => 'button', - 'id' => 'button', - 'value' => 'true', - 'type' => 'reset', - 'content' => 'Reset' + 'name' => 'button', + 'id' => 'button', + 'value' => 'true', + 'type' => 'reset', + 'content' => 'Reset' ); echo form_button($data); // Would produce: <button name="button" id="button" value="true" type="reset">Reset</button> If you would like your form to contain some additional data, like -JavaScript, you can pass it as a string in the third parameter: - -:: +JavaScript, you can pass it as a string in the third parameter:: - $js = 'onClick="some_function()"'; + $js = 'onClick="some_function()"'; echo form_button('mybutton', 'Click Me', $js); form_close() ============ +.. php:function:: form_close($extra = '') + + :param string $extra: Anything to append after the closing tag, *as is* + :returns: string + Produces a closing </form> tag. The only advantage to using this function is it permits you to pass data to it which will be added below -the tag. For example +the tag. For example:: -:: - - $string = "</div></div>"; + $string = '</div></div>'; echo form_close($string); // Would produce: </form> </div></div> +form_prep() +=========== + +.. php:function:: form_prep($str = '', $is_textarea = FALSE) + + :param string $str: Value to escape + :param bool $is_textarea: Whether we're preparing for <textarea> or a regular input tag + :returns: string + +Allows you to safely use HTML and characters such as quotes within form +elements without breaking out of the form. + +Consider this example:: + + $string = 'Here is a string containing "quoted" text.'; + <input type="text" name="myform" value="$string" /> + +Since the above string contains a set of quotes it will cause the form +to break. The ``form_prep()`` function converts HTML so that it can be used +safely:: + + <input type="text" name="myform" value="<?php echo form_prep($string); ?>" /> + +.. note:: If you use any of the form helper functions listed in this page the form + values will be prepped automatically, so there is no need to call this + function. Use it only if you are creating your own form elements. + set_value() =========== +.. php:function:: set_value($field = '', $default = '', $is_textarea = FALSE) + + :param string $field: Field name + :param string $default: Default value + :param bool $is_textarea: Whether we're setting <textarea> content + :returns: string + 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 second (optional) parameter allows you to set a default value for the -form. Example +form. -:: +Example:: - <input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" /> + <input type="text" name="quantity" value="<?=set_value('quantity', '0');?>" size="50" /> The above form will show "0" when loaded for the first time. set_select() ============ +.. php:function:: set_select($field = '', $value = '', $default = FALSE) + + :param string $field: Field name + :param string $value: Value to check for + :param string $default: Whether the value is also a default one + :returns: string + 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 -of the select menu, the second parameter must contain the value of each -item, and the third (optional) parameter lets you set an item as the -default (use boolean TRUE/FALSE). +menu item that was selected. -Example +The first parameter must contain the name of the select menu, the second +parameter must contain the value of each item, and the third (optional) +parameter lets you set an item as the default (use boolean TRUE/FALSE). -:: +Example:: <select name="myselect"> <option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option> @@ -499,12 +631,20 @@ Example 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 +.. php:function:: set_checkbox($field = '', $value = '', $default = FALSE) + + :param string $field: Field name + :param string $value: Value to check for + :param string $default: Whether the value is also a default one + :returns: string + +Permits you to display a checkbox in the state it was submitted. + +The first parameter must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter -lets you set an item as the default (use boolean TRUE/FALSE). Example +lets you set an item as the default (use boolean TRUE/FALSE). -:: +Example:: <input type="checkbox" name="mycheck" value="1" <?php echo set_checkbox('mycheck', '1'); ?> /> <input type="checkbox" name="mycheck" value="2" <?php echo set_checkbox('mycheck', '2'); ?> /> @@ -512,37 +652,71 @@ lets you set an item as the default (use boolean TRUE/FALSE). Example set_radio() =========== +.. php:function:: set_radio($field = '', $value = '', $default = FALSE) + + :param string $field: Field name + :param string $value: Value to check for + :param string $default: Whether the value is also a default one + :returns: string + Permits you to display radio buttons in the state they were submitted. -This function is identical to the **set_checkbox()** function above. +This function is identical to the :php:func:`set_checkbox()` function above. -:: +Example:: <input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> /> <input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> /> -.. note:: If you are using the Form Validation class, you must always specify a rule for your field, - even if empty, in order for the set_*() functions to work. This is because if a Form Validation object - is defined, the control for set_*() is handed over to a method of the class instead of the generic helper - function. +.. note:: If you are using the Form Validation class, you must always specify + a rule for your field, even if empty, in order for the ``set_*()`` + functions to work. This is because if a Form Validation object is + defined, the control for ``set_*()`` is handed over to a method of the + class instead of the generic helper function. -Escaping field values -===================== +form_error() +============ -You may need to use HTML and characters such as quotes within form -elements. In order to do that safely, you'll need to use -:doc:`common function <../general/common_functions>` ``html_escape()``. +.. php:function:: form_error($field = '', $prefix = '', $suffix = '') -Consider the following example:: + :param string $field: Field name + :param string $prefix: Error opening tag + :param string $suffix: Error closing tag + :returns: string - $string = 'Here is a string containing "quoted" text.'; - <input type="text" name="myform" value="$string" /> +Returns a validation error message from the :doc:`Form Validation Library +<../libraries/form_validation>`, associated with the specified field name. +You can optionally specify opening and closing tag(s) to put around the error +message. -Since the above string contains a set of quotes it will cause the form -to break. The ``html_escape()`` function converts HTML so that it can be -used safely:: +Example:: - <input type="text" name="myform" value="<?php echo html_escape($string); ?>" /> + // Assuming that the 'username' field value was incorrect: + echo form_error('myfield', '<div class="error">', '</div>'); -.. note:: If you use any of the form helper functions listed in this page, the form - values will be prepped automatically, so there is no need to call this - function. Use it only if you are creating your own form elements.
\ No newline at end of file + // Would produce: <div class="error">Error message associated with the "username" field.</div> + +validation_errors() +=================== + +.. php:function:: validation_errors($prefix = '', $suffix = '') + + :param string $prefix: Error opening tag + :param string $suffix: Error closing tag + :returns: string + +Similarly to the :php:func:`form_error()` function, returns all validation +error messages produced by the :doc:`Form Validation Library +<../libraries/form_validation>`, with optional opening and closing tags +around each of the messages. + +Example:: + + echo validation_errors('<span class="error">', '</span>'); + + /* + Would produce, e.g.: + + <span class="error">The "email" field doesn't contain a valid e-mail address!</span> + <span class="error">The "password" field doesn't match the "repeat_password" field!</span> + + */
\ No newline at end of file diff --git a/user_guide_src/source/helpers/html_helper.rst b/user_guide_src/source/helpers/html_helper.rst index 17c28cd2a..df53ebd2f 100644 --- a/user_guide_src/source/helpers/html_helper.rst +++ b/user_guide_src/source/helpers/html_helper.rst @@ -19,6 +19,11 @@ The following functions are available: br() ==== +.. php:function:: br($count = 1) + + :param int $count: Number of times to repeat the tag + :returns: string + Generates line break tags (<br />) based on the number you submit. Example:: @@ -29,7 +34,14 @@ The above would produce: <br /><br /><br /> heading() ========= -Lets you create HTML <h1> tags. The first parameter will contain the +.. php:function:: heading($data = '', $h = '1', $attributes = '') + + :param string $data: Content + :param string $h: Heading level + :param array $attributes: HTML attributes + :returns: string + +Lets you create HTML heading tags. The first parameter will contain the data, the second the size of the heading. Example:: echo heading('Welcome!', 3); @@ -37,9 +49,7 @@ data, the second the size of the heading. Example:: The above would produce: <h3>Welcome!</h3> Additionally, in order to add attributes to the heading tag such as HTML -classes, ids or inline styles, a third parameter is available. - -:: +classes, ids or inline styles, a third parameter is available:: echo heading('Welcome!', 3, 'class="pink"') @@ -48,28 +58,31 @@ The above code produces: <h3 class="pink">Welcome!<<h3> img() ===== -Lets you create HTML <img /> tags. The first parameter contains the -image source. Example +.. php:function:: img($src = '', $index_page = FALSE, $attributes = '') -:: + :param string $src: Image source data + :param bool $index_page: Whether to treat $src as a routed URI string + :param array $attributes: HTML attributes + :returns: string + +Lets you create HTML <img /> tags. The first parameter contains the +image source. Example:: echo img('images/picture.jpg'); // gives <img src="http://site.com/images/picture.jpg" /> There is an optional second parameter that is a TRUE/FALSE value that -specifics if the src should have the page specified by -$config['index_page'] added to the address it creates. Presumably, this -would be if you were using a media controller. - -:: +specifics if the *src* should have the page specified by +``$config['index_page']`` added to the address it creates. +Presumably, this would be if you were using a media controller:: echo img('images/picture.jpg', TRUE); // gives <img src="http://site.com/index.php/images/picture.jpg" alt="" /> -Additionally, an associative array can be passed to the img() function -for complete control over all attributes and values. If an alt attribute +Additionally, an associative array can be passed to the ``img()`` function +for complete control over all attributes and values. If an *alt* attribute is not provided, CodeIgniter will generate an empty string. -:: +Example:: $image_properties = array( 'src' => 'images/picture.jpg', @@ -81,128 +94,136 @@ is not provided, CodeIgniter will generate an empty string. 'rel' => 'lightbox' ); - img($image_properties); // <img src="http://site.com/index.php/images/picture.jpg" alt="Me, demonstrating how to eat 4 slices of pizza at one time" class="post_images" width="200" height="200" title="That was quite a night" rel="lightbox" /> + img($image_properties); + // <img src="http://site.com/index.php/images/picture.jpg" alt="Me, demonstrating how to eat 4 slices of pizza at one time" class="post_images" width="200" height="200" title="That was quite a night" rel="lightbox" /> link_tag() -=========== +========== -Lets you create HTML <link /> tags. This is useful for stylesheet links, -as well as other links. The parameters are href, with optional rel, -type, title, media and index_page. index_page is a TRUE/FALSE value -that specifics if the href should have the page specified by -$config['index_page'] added to the address it creates. +.. php:function:: ling_tag($href = '', $rel = 'stylesheet', $type = 'text/css', $title = '', $media = '', $index_page = FALSE) -:: + :param string $href: What are we linking to + :param string $rel: Relation type + :param string $type: Type of the related document + :param string $title: Link title + :param string $media: Media type + :param bool $index_page: Whether to treat $src as a routed URI string + :returns: string - echo link_tag('css/mystyles.css'); // gives <link href="http://site.com/css/mystyles.css" rel="stylesheet" type="text/css" /> +Lets you create HTML <link /> tags. This is useful for stylesheet links, +as well as other links. The parameters are *href*, with optional *rel*, +*type*, *title*, *media* and *index_page*. + +*index_page* is a boolean value that specifies if the *href* should have +the page specified by ``$config['index_page']`` added to the address it creates. +Example:: -Further examples + echo link_tag('css/mystyles.css'); + // gives <link href="http://site.com/css/mystyles.css" rel="stylesheet" type="text/css" /> -:: - echo link_tag('favicon.ico', 'shortcut icon', 'image/ico'); // <link href="http://site.com/favicon.ico" rel="shortcut icon" type="image/ico" /> +Further examples:: - echo link_tag('feed', 'alternate', 'application/rss+xml', 'My RSS Feed'); // <link href="http://site.com/feed" rel="alternate" type="application/rss+xml" title="My RSS Feed" /> + echo link_tag('favicon.ico', 'shortcut icon', 'image/ico'); + // <link href="http://site.com/favicon.ico" rel="shortcut icon" type="image/ico" /> -Additionally, an associative array can be passed to the link() function -for complete control over all attributes and values. + echo link_tag('feed', 'alternate', 'application/rss+xml', 'My RSS Feed'); + // <link href="http://site.com/feed" rel="alternate" type="application/rss+xml" title="My RSS Feed" /> -:: +Additionally, an associative array can be passed to the ``link()`` function +for complete control over all attributes and values:: $link = array( - 'href' => 'css/printer.css', - 'rel' => 'stylesheet', - 'type' => 'text/css', - 'media' => 'print' + 'href' => 'css/printer.css', + 'rel' => 'stylesheet', + 'type' => 'text/css', + 'media' => 'print' ); - echo link_tag($link); // <link href="http://site.com/css/printer.css" rel="stylesheet" type="text/css" media="print" /> - + echo link_tag($link); + // <link href="http://site.com/css/printer.css" rel="stylesheet" type="text/css" media="print" /> nbs() ===== -Generates non-breaking spaces ( ) based on the number you submit. -Example +.. php:function:: nbs($num = 1) -:: + :param int $num: Number of space entities to produce + :returns: string - echo nbs(3); +Generates non-breaking spaces ( ) based on the number you submit. +Example:: -The above would produce + echo nbs(3); -:: +The above would produce:: -ol() and ul() +ul() and ol() ============= -Permits you to generate ordered or unordered HTML lists from simple or -multi-dimensional arrays. Example +.. php:function:: ul($list, $attributes = '') -:: + :param array $list: List entries + :param array $attributes: HTML attributes + :returns: string - $this->load->helper('html'); +Permits you to generate ordered or unordered HTML lists from simple or +multi-dimensional arrays. Example:: - $list = array( - 'red', - 'blue', - 'green', - 'yellow' + $list = array( + 'red', + 'blue', + 'green', + 'yellow' ); - $attributes = array( - 'class' => 'boldlist', - 'id' => 'mylist' + $attributes = array( + 'class' => 'boldlist', + 'id' => 'mylist' ); echo ul($list, $attributes); -The above code will produce this - -:: +The above code will produce this:: - <ul class="boldlist" id="mylist"> - <li>red</li> - <li>blue</li> - <li>green</li> + <ul class="boldlist" id="mylist"> + <li>red</li> + <li>blue</li> + <li>green</li> <li>yellow</li> </ul> -Here is a more complex example, using a multi-dimensional array - -:: - - $this->load->helper('html'); +Here is a more complex example, using a multi-dimensional array:: - $attributes = array( - 'class' => 'boldlist', - 'id' => 'mylist' + $attributes = array( + 'class' => 'boldlist', + 'id' => 'mylist' ); - $list = array( - 'colors' => array( - 'red', - 'blue', - 'green' + $list = array( + 'colors' => array( + 'red', + 'blue', + 'green' ), - 'shapes' => array( - 'round', - 'square', - 'circles' => array( + 'shapes' => array( + 'round', + 'square', + 'circles' => array( 'ellipse', 'oval', 'sphere' - ) - ), - 'moods' => array( - 'happy', - 'upset' => array( + ) + ), + 'moods' => array( + 'happy', + 'upset' => array( 'defeated' => array( - 'dejected', + 'dejected', 'disheartened', 'depressed' ), @@ -215,59 +236,74 @@ Here is a more complex example, using a multi-dimensional array echo ul($list, $attributes); -The above code will produce this - -:: - - <ul class="boldlist" id="mylist"> - <li>colors - <ul> - <li>red</li> - <li>blue</li> - <li>green</li> - </ul> - </li> - <li>shapes - <ul> - <li>round</li> - <li>suare</li> - <li>circles - <ul> - <li>elipse</li> - <li>oval</li> - <li>sphere</li> - </ul> - </li> - </ul> - </li> - <li>moods - <ul> - <li>happy</li> - <li>upset - <ul> - <li>defeated - <ul> +The above code will produce this:: + + <ul class="boldlist" id="mylist"> + <li>colors + <ul> + <li>red</li> + <li>blue</li> + <li>green</li> + </ul> + </li> + <li>shapes + <ul> + <li>round</li> + <li>suare</li> + <li>circles + <ul> + <li>elipse</li> + <li>oval</li> + <li>sphere</li> + </ul> + </li> + </ul> + </li> + <li>moods + <ul> + <li>happy</li> + <li>upset + <ul> + <li>defeated + <ul> <li>dejected</li> <li>disheartened</li> <li>depressed</li> </ul> </li> <li>annoyed</li> - <li>cross</li> - <li>angry</li> - </ul> - </li> - </ul> + <li>cross</li> + <li>angry</li> + </ul> + </li> + </ul> </li> </ul> +.. php:function:: ol($list, $attributes = '') + + :param array $list: List entries + :param array $attributes: HTML attributes + :returns: string + +Identical to :php:func:`ul()`, only it produces the <ol> tag for +ordered lists instead of <ul>. + meta() ====== +.. php:function:: meta($name = '', $content = '', $type = 'name', $newline = "\n") + + :param string $name: Meta name + :param string $content: Meta content + :param string $type: Meta type + :param string $newline: Newline character + :returns: string + Helps you generate meta tags. You can pass strings to the function, or -simple arrays, or multidimensional ones. Examples +simple arrays, or multidimensional ones. -:: +Examples:: echo meta('description', 'My Great site'); // Generates: <meta name="description" content="My Great Site" /> @@ -279,7 +315,7 @@ simple arrays, or multidimensional ones. Examples echo meta(array('name' => 'robots', 'content' => 'no-cache')); // Generates: <meta name="robots" content="no-cache" /> - $meta = array( + $meta = array( array( 'name' => 'robots', 'content' => 'no-cache' @@ -291,7 +327,7 @@ simple arrays, or multidimensional ones. Examples array( 'name' => 'keywords', 'content' => 'love, passion, intrigue, deception' - ), + ), array( 'name' => 'robots', 'content' => 'no-cache' @@ -313,10 +349,14 @@ simple arrays, or multidimensional ones. Examples doctype() ========= +.. php:function:: doctype($type = 'xhtml1-strict') + + :param string $type: Doctype name + Helps you generate document type declarations, or DTD's. XHTML 1.0 Strict is used by default, but many doctypes are available. -:: +Example:: echo doctype(); // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> diff --git a/user_guide_src/source/helpers/inflector_helper.rst b/user_guide_src/source/helpers/inflector_helper.rst index cc46a1851..1f54b76c0 100644 --- a/user_guide_src/source/helpers/inflector_helper.rst +++ b/user_guide_src/source/helpers/inflector_helper.rst @@ -10,9 +10,7 @@ words to plural, singular, camel case, etc. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('inflector'); @@ -21,65 +19,81 @@ The following functions are available: singular() ========== -Changes a plural word to singular. Example +.. php:function:: singular($str) + + :param string $str: Input string + :returns: string -:: +Changes a plural word to singular. Example:: - $word = "dogs"; - echo singular($word); // Returns "dog" + echo singular('dogs'); // Prints 'dog' plural() ======== -Changes a singular word to plural. Example - -:: - - $word = "dog"; - echo plural($word); // Returns "dogs" +.. php:function:: plural($str) -To force a word to end with "es" use a second "true" argument. + :param string $str: Input string + :returns: string -:: +Changes a singular word to plural. Example:: - $word = "pass"; - echo plural($word, TRUE); // Returns "passes" + echo plural('dog'); // Prints 'dogs' camelize() ========== -Changes a string of words separated by spaces or underscores to camel -case. Example +.. php:function:: camelize($str) + + :param string $str: Input string + :returns: string -:: +Changes a string of words separated by spaces or underscores to camel +case. Example:: - $word = "my_dog_spot"; - echo camelize($word); // Returns "myDogSpot" + echo camelize('my_dog_spot'); // Prints 'myDogSpot' underscore() ============ -Takes multiple words separated by spaces and underscores them. Example +.. php:function:: camelize($str) -:: + :param string $str: Input string + :returns: string - $word = "my dog spot"; - echo underscore($word); // Returns "my_dog_spot" +Takes multiple words separated by spaces and underscores them. +Example:: + + echo underscore('my dog spot'); // Prints 'my_dog_spot' humanize() ========== +.. php:function:: camelize($str) + + :param string $str: Input string + :param string $separator: Input separator + :returns: string + Takes multiple words separated by underscores and adds spaces between -them. Each word is capitalized. Example +them. Each word is capitalized. + +Example:: + + echo humanize('my_dog_spot'); // Prints 'My Dog Spot' + +To use dashes instead of underscores:: + + echo humanize('my-dog-spot', '-'); // Prints 'My Dog Spot' -:: +is_countable() +============== - $word = "my_dog_spot"; - echo humanize($word); // Returns "My Dog Spot" +.. php:function:: is_countable($word) -To use dashes instead of underscores + :param string $word: Input string + :returns: bool -:: +Checks if the given word has a plural version. Example:: - $word = "my-dog-spot"; - echo humanize($word, '-'); // Returns "My Dog Spot"
\ No newline at end of file + is_countable('equipment'); // Returns FALSE
\ No newline at end of file diff --git a/user_guide_src/source/helpers/language_helper.rst b/user_guide_src/source/helpers/language_helper.rst index b7b23d149..8b039374d 100644 --- a/user_guide_src/source/helpers/language_helper.rst +++ b/user_guide_src/source/helpers/language_helper.rst @@ -10,24 +10,27 @@ language files. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('language'); The following functions are available: -lang('language line', 'element id') -=================================== +lang() +====== + +.. php:function:: lang($line, $id = '') + + :param string $line: Language line key + :param string $id: ID of the element we're creating a label for + :returns: string This function returns a line of text from a loaded language file with -simplified syntax that may be more desirable for view files than calling -`$this->lang->line()`. The optional second parameter will also output a -form label for you. Example +simplified syntax that may be more desirable for view files than +``CI_Lang::line()``. +The optional second parameter will also output a form label for you. -:: +Example:: echo lang('language_key', 'form_item_id'); - // becomes <label for="form_item_id">language_key</label> - + // becomes <label for="form_item_id">language_key</label>
\ No newline at end of file diff --git a/user_guide_src/source/helpers/number_helper.rst b/user_guide_src/source/helpers/number_helper.rst index af6cdad57..8e0ebda5e 100644 --- a/user_guide_src/source/helpers/number_helper.rst +++ b/user_guide_src/source/helpers/number_helper.rst @@ -10,9 +10,7 @@ numeric data. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('number'); @@ -21,25 +19,27 @@ The following functions are available: byte_format() ============= -Formats a numbers as bytes, based on size, and adds the appropriate -suffix. Examples +.. php:function:: byte_format($num, $precision = 1) + + :param mixed $num: Number of bytes + :param int $precision: Floating point precision + :returns: string -:: +Formats numbers as bytes, based on size, and adds the appropriate +suffix. Examples:: - echo byte_format(456); // Returns 456 Bytes - echo byte_format(4567); // Returns 4.5 KB - echo byte_format(45678); // Returns 44.6 KB - echo byte_format(456789); // Returns 447.8 KB - echo byte_format(3456789); // Returns 3.3 MB - echo byte_format(12345678912345); // Returns 1.8 GB + echo byte_format(456); // Returns 456 Bytes + echo byte_format(4567); // Returns 4.5 KB + echo byte_format(45678); // Returns 44.6 KB + echo byte_format(456789); // Returns 447.8 KB + echo byte_format(3456789); // Returns 3.3 MB + echo byte_format(12345678912345); // Returns 1.8 GB echo byte_format(123456789123456789); // Returns 11,228.3 TB An optional second parameter allows you to set the precision of the -result. - -:: +result:: echo byte_format(45678, 2); // Returns 44.61 KB .. note:: The text generated by this function is found in the following - language file: language/<your_lang>/number_lang.php + language file: `language/<your_lang>/number_lang.php`
\ No newline at end of file diff --git a/user_guide_src/source/helpers/path_helper.rst b/user_guide_src/source/helpers/path_helper.rst index 847f5a08b..3a271b28f 100644 --- a/user_guide_src/source/helpers/path_helper.rst +++ b/user_guide_src/source/helpers/path_helper.rst @@ -10,9 +10,7 @@ file paths on the server. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('path'); @@ -21,23 +19,28 @@ The following functions are available: set_realpath() ============== -Checks to see if the path exists. This function will return a server -path without symbolic links or relative directory structures. An -optional second argument will cause an error to be triggered if the path -cannot be resolved. +.. php:function:: set_realpath($path, $check_existance = FALSE) + + :param string $path: Path + :param bool $check_existance: Whether to check if the path actually exists + :returns: string + +This function will return a server path without symbolic links or +relative directory structures. An optional second argument will +cause an error to be triggered if the path cannot be resolved. -:: +Examples:: $file = '/etc/php5/apache2/php.ini'; - echo set_realpath($file); // returns "/etc/php5/apache2/php.ini" + echo set_realpath($file); // Prints '/etc/php5/apache2/php.ini' $non_existent_file = '/path/to/non-exist-file.txt'; - echo set_realpath($non_existent_file, TRUE); // shows an error, as the path cannot be resolved - echo set_realpath($non_existent_file, FALSE); // returns "/path/to/non-exist-file.txt" + echo set_realpath($non_existent_file, TRUE); // Shows an error, as the path cannot be resolved + echo set_realpath($non_existent_file, FALSE); // Prints '/path/to/non-exist-file.txt' $directory = '/etc/php5'; - echo set_realpath($directory); // returns "/etc/php5/" + echo set_realpath($directory); // Prints '/etc/php5/' $non_existent_directory = '/path/to/nowhere'; - echo set_realpath($non_existent_directory, TRUE); // shows an error, as the path cannot be resolved - echo set_realpath($non_existent_directory, FALSE); // returns "/path/to/nowhere" + echo set_realpath($non_existent_directory, TRUE); // Shows an error, as the path cannot be resolved + echo set_realpath($non_existent_directory, FALSE); // Prints '/path/to/nowhere'
\ No newline at end of file diff --git a/user_guide_src/source/helpers/security_helper.rst b/user_guide_src/source/helpers/security_helper.rst index ec0be28b3..21bf53490 100644 --- a/user_guide_src/source/helpers/security_helper.rst +++ b/user_guide_src/source/helpers/security_helper.rst @@ -9,9 +9,7 @@ The Security Helper file contains security related functions. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('security'); @@ -20,25 +18,47 @@ The following functions are available: xss_clean() =========== -Provides Cross Site Script Hack filtering. This function is an alias to -the one in the :doc:`Input class <../libraries/input>`. More info can -be found there. +.. php:function:: xss_clean($str, $is_image = FALSE) + + :param string $str: Input data + :param bool $is_image: Whether we're dealing with an image + :returns: string + +Provides Cross Site Script Hack filtering. + +This function is an alias for ``CI_Input::xss_clean()``. For more info, +please see the :doc:`Input Library <../libraries/input>` documentation. sanitize_filename() =================== -Provides protection against directory traversal. This function is an -alias to the one in the :doc:`Security class <../libraries/security>`. -More info can be found there. +.. php:function:: sanitize_filename($filename) + + :param string $filename: Filename + :returns: string + +Provides protection against directory traversal. + +This function is an alias for ``CI_Security::sanitize_filename()``. +For more info, please see the :doc:`Security Library <../libraries/security>` +documentation. do_hash() ========= +.. php:function:: do_hash($str, $type = 'sha1') + + :param string $str: Input + :param string $type: Algorithm + :returns: string + Permits you to create one way hashes suitable for encrypting -passwords. Will create SHA1 by default. See `hash_algos() <http://php.net/function.hash_algos>`_ +passwords. Will use SHA1 by default. + +See `hash_algos() <http://php.net/function.hash_algos>`_ for a full list of supported algorithms. -:: +Examples:: $str = do_hash($str); // SHA1 $str = do_hash($str, 'md5'); // MD5 @@ -51,20 +71,34 @@ for a full list of supported algorithms. strip_image_tags() ================== -This is a security function that will strip image tags from a string. It -leaves the image URL as plain text. +.. php:function:: strip_image_tags($str) + + :param string $str: Input + :returns: string + +This is a security function that will strip image tags from a string. +It leaves the image URL as plain text. -:: +Example:: $string = strip_image_tags($string); +This function is an alias for ``CI_Security::strip_image_tags()``. For +more info, please see the :doc:`Security Library <../libraries/security>` +documentation. + encode_php_tags() ================= -This is a security function that converts PHP tags to entities. Note: If -you use the XSS filtering function it does this automatically. +.. php:function:: encode_php_tags($str) + + :param string $str: Input + :returns: string + +This is a security function that converts PHP tags to entities. -:: +.. note: :php:func:`xss_clean()` does this automatically, if you use it. - $string = encode_php_tags($string); +Example:: + $string = encode_php_tags($string);
\ No newline at end of file diff --git a/user_guide_src/source/helpers/smiley_helper.rst b/user_guide_src/source/helpers/smiley_helper.rst index 941ba11e3..13841e8bd 100644 --- a/user_guide_src/source/helpers/smiley_helper.rst +++ b/user_guide_src/source/helpers/smiley_helper.rst @@ -10,9 +10,7 @@ The Smiley Helper file contains functions that let you manage smileys Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('smiley'); @@ -36,10 +34,11 @@ smileys next to a form field. This example requires that you first download and install the smiley images, then create a controller and the View as described. -.. important:: Before you begin, please `download the smiley images <http://codeigniter.com/download_files/smileys.zip>`_ - and put them in a publicly accessible place on your server. This helper - also assumes you have the smiley replacement array located at - `application/config/smileys.php` +.. important:: Before you begin, please `download the smiley images + <http://codeigniter.com/download_files/smileys.zip>`_ + and put them in a publicly accessible place on your server. + This helper also assumes you have the smiley replacement array + located at `application/config/smileys.php` The Controller -------------- @@ -47,18 +46,17 @@ The Controller In your `application/controllers/` folder, create a file called smileys.php and place the code below in it. -.. important:: Change the URL in the `get_clickable_smileys()` +.. important:: Change the URL in the :php:func:`get_clickable_smileys()` function below so that it points to your smiley folder. -You'll notice that in addition to the smiley helper we are using the :doc:`Table Class <../libraries/table>`. - -:: +You'll notice that in addition to the smiley helper, we are also using +the :doc:`Table Class <../libraries/table>`:: <?php class Smileys extends CI_Controller { - function index() + public function index() { $this->load->helper('smiley'); $this->load->library('table'); @@ -69,12 +67,11 @@ You'll notice that in addition to the smiley helper we are using the :doc:`Table $data['smiley_table'] = $this->table->generate($col_array); $this->load->view('smiley_view', $data); } + } In your `application/views/` folder, create a file called `smiley_view.php` -and place this code in it: - -:: +and place this code in it:: <html> <head> @@ -102,59 +99,66 @@ links a generic name that will be tied to a specific id in your view. $image_array = get_smiley_links("http://example.com/images/smileys/", "comment_textarea_alias"); -To map the alias to the field id, pass them both into the `smiley_js` -function - -:: +To map the alias to the field id, pass them both into the +:php:func:`smiley_js()` function:: $image_array = smiley_js("comment_textarea_alias", "comments"); -****************** -Function Reference -****************** - get_clickable_smileys() ======================= +.. php:function:: get_clickable_smileys($image_url, $alias = '', $smileys = NULL) + + :param string $image_url: URL path to the smileys directory + :param string $alias: Field alias + :returns: array + Returns an array containing your smiley images wrapped in a clickable link. You must supply the URL to your smiley folder and a field id or field alias. -:: +Example:: $image_array = get_smiley_links("http://example.com/images/smileys/", "comment"); -Note: Usage of this function without the second parameter, in -combination with `js_insert_smiley` has been deprecated. - smiley_js() =========== +.. php:function:: smiley_js($alias = '', $field_id = '', $inline = TRUE) + + :param string $alias: Field alias + :param string $field_id: Field ID + :param bool $inline: Whether we're inserting an inline smiley + Generates the JavaScript that allows the images to be clicked and inserted into a form field. If you supplied an alias instead of an id when generating your smiley links, you need to pass the alias and corresponding form id into the function. This function is designed to be placed into the <head> area of your web page. -:: +Example:: <?php echo smiley_js(); ?> -Note: This function replaces `js_insert_smiley`, which has been -deprecated. - parse_smileys() =============== +.. php:function:: parse_smileys($str = '', $image_url = '', $smileys = NULL) + + :param string $str: Text containing smiley codes + :param string $image_url: URL path to the smileys directory + :param array $smileys: An array of smileys + :returns: string + Takes a string of text as input and replaces any contained plain text smileys into the image equivalent. The first parameter must contain your string, the second must contain the URL to your smiley folder -:: +Example:: $str = 'Here are some simileys: :-) ;-)'; $str = parse_smileys($str, "http://example.com/images/smileys/"); echo $str; -.. |smile!| image:: ../images/smile.gif +.. |smile!| image:: ../images/smile.gif
\ No newline at end of file diff --git a/user_guide_src/source/helpers/string_helper.rst b/user_guide_src/source/helpers/string_helper.rst index 530af2f89..d0d302476 100644 --- a/user_guide_src/source/helpers/string_helper.rst +++ b/user_guide_src/source/helpers/string_helper.rst @@ -10,9 +10,7 @@ strings. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('string'); @@ -21,39 +19,48 @@ The following functions are available: random_string() =============== +.. php:function:: random_string($type = 'alnum', $len = 8) + + :param string $type: Randomization type + :param int $len: Output string length + :returns: string + Generates a random string based on the type and length you specify. Useful for creating passwords or generating random hashes. The first parameter specifies the type of string, the second parameter specifies the length. The following choices are available: -alpha, alunum, numeric, nozero, unique, md5, encrypt and sha1 - - **alpha**: A string with lower and uppercase letters only. - **alnum**: Alpha-numeric string with lower and uppercase characters. +- **basic**: A random number based on ``mt_rand()``. - **numeric**: Numeric string. - **nozero**: Numeric string with no zeros. -- **unique**: Encrypted with MD5 and uniqid(). Note: The length - parameter is not available for this type. Returns a fixed length 32 - character string. -- **sha1**: An encrypted random number based on ``sha1()``. - -Usage example +- **md5**: An encrypted random number based on ``md5()`` (fixed length of 32). +- **sha1**: An encrypted random number based on ``sha1()`` (fixed length of 40). -:: +Usage example:: echo random_string('alnum', 16); +.. note:: Usage of the *unique* and *encrypt* types is DEPRECATED. They + are just aliases for *md5* and *sha1* respectively. + increment_string() ================== +.. php:function:: increment_string($str, $separator = '_', $first = 1) + + :param string $str: Input string + :param string $separator: Separator to append a duplicate number with + :param int $first: Starting number + :returns: string + Increments a string by appending a number to it or increasing the number. Useful for creating "copies" or a file or duplicating database content which has unique titles or slugs. -Usage example - -:: +Usage example:: echo increment_string('file', '_'); // "file_1" echo increment_string('file', '-', 2); // "file-2" @@ -62,10 +69,13 @@ Usage example alternator() ============ -Allows two or more items to be alternated between, when cycling through -a loop. Example +.. php:function:: alternator($args) -:: + :param mixed $args: A variable number of arguments + :returns: mixed + +Allows two or more items to be alternated between, when cycling through +a loop. Example:: for ($i = 0; $i < 10; $i++) { @@ -88,11 +98,16 @@ your loop the next item will be returned. repeater() ========== -Generates repeating copies of the data you submit. Example +.. php:function:: repeater($data, $num = 1) -:: + :param string $data: Input + :param int $num: Number of times to repeat + :returns: string + +Generates repeating copies of the data you submit. Example:: - $string = "\n"; echo repeater($string, 30); + $string = "\n"; + echo repeater($string, 30); The above would generate 30 newlines. @@ -102,10 +117,15 @@ The above would generate 30 newlines. reduce_double_slashes() ======================= +.. php:function:: reduce_double_slashes($str) + + :param string $str: Input string + :returns: string + Converts double slashes in a string to a single slash, except those -found in http://. Example +found in URL protocol prefixes (e.g. http://). -:: +Example:: $string = "http://example.com//index.php"; echo reduce_double_slashes($string); // results in "http://example.com/index.php" @@ -113,16 +133,14 @@ found in http://. Example strip_slashes() =============== -Removes any slashes from a string. Example - -:: +.. php:function:: strip_slashes($data) - $str = "Is your name O\'reilly?"; - echo strip_slashes($str); // results in Is your name O'reilly? + :param array $data: Input + :returns: array -You can also use an array. Example +Removes any slashes from an array of strings. -:: +Example:: $str = array( 'question' => 'Is your name O\'reilly?', @@ -131,60 +149,66 @@ You can also use an array. Example $str = strip_slashes($str); -The above will return the following array: - -:: +The above will return the following array:: array( 'question' => "Is your name O'reilly?", 'answer' => "No, my name is O'connor." ); +.. note:: For historical reasons, this function will also accept + and handle string inputs. This however makes it just an + alias for ``stripslashes()``. + trim_slashes() ============== -Removes any leading/trailing slashes from a string. Example +.. php:function:: trim_slashes($str) -:: + :param string $str: Input string + :returns: string + +Removes any leading/trailing slashes from a string. Example:: $string = "/this/that/theother/"; echo trim_slashes($string); // results in this/that/theother +.. note:: This function is DEPRECATED. Use the native ``trim()`` instead: + | + | trim($str, '/'); reduce_multiples() ================== +.. php:function:: reduce_multiples($str, $character = '', $trim = FALSE) + + :param string $str: Text to search in + :param string $character: Character to reduce + :param bool $trim: Whether to also trim the specified character + :returns: string + Reduces multiple instances of a particular character occuring directly after each other. Example:: $string = "Fred, Bill,, Joe, Jimmy"; $string = reduce_multiples($string,","); //results in "Fred, Bill, Joe, Jimmy" -The function accepts the following parameters: - -:: - - reduce_multiples(string: text to search in, string: character to reduce, boolean: whether to remove the character from the front and end of the string) - -The first parameter contains the string in which you want to reduce the -multiplies. The second parameter contains the character you want to have -reduced. The third parameter is FALSE by default; if set to TRUE it will -remove occurences of the character at the beginning and the end of the -string. Example: - -:: +If the third parameter is set to TRUE it will remove occurences of the +character at the beginning and the end of the string. Example:: $string = ",Fred, Bill,, Joe, Jimmy,"; $string = reduce_multiples($string, ", ", TRUE); //results in "Fred, Bill, Joe, Jimmy" - quotes_to_entities() ==================== -Converts single and double quotes in a string to the corresponding HTML -entities. Example +.. php:function:: quotes_to_entities($str) -:: + :param string $str: Input string + :returns: string + +Converts single and double quotes in a string to the corresponding HTML +entities. Example:: $string = "Joe's \"dinner\""; $string = quotes_to_entities($string); //results in "Joe's "dinner"" @@ -192,8 +216,12 @@ entities. Example strip_quotes() ============== +.. php:function:: strip_quotes($str) + + :param string $str: Input string + :returns: string + Removes single and double quotes from a string. Example:: $string = "Joe's \"dinner\""; - $string = strip_quotes($string); //results in "Joes dinner" - + $string = strip_quotes($string); //results in "Joes dinner"
\ No newline at end of file diff --git a/user_guide_src/source/helpers/text_helper.rst b/user_guide_src/source/helpers/text_helper.rst index 8cb2d6f96..aec36c9a7 100644 --- a/user_guide_src/source/helpers/text_helper.rst +++ b/user_guide_src/source/helpers/text_helper.rst @@ -10,9 +10,7 @@ text. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('text'); @@ -21,7 +19,14 @@ The following functions are available: word_limiter() ============== -Truncates a string to the number of **words** specified. Example:: +.. php:function:: word_limiter($str, $limit = 100, $end_char = '…') + + :param string $str: Input string + :param int $limit: Limit + :param string $end_char: End character (usually an ellipsis) + :returns: string + +Truncates a string to the number of *words* specified. Example:: $string = "Here is a nice text string consisting of eleven words."; $string = word_limiter($string, 4); @@ -33,11 +38,18 @@ default it adds an ellipsis. character_limiter() =================== -Truncates a string to the number of **characters** specified. It +.. php:function:: character_limiter($str, $n = 500, $end_char = '…') + + :param string $str: Input string + :param int $n: Number of characters + :param string $end_char: End character (usually an ellipsis) + :returns: string + +Truncates a string to the number of *characters* specified. It maintains the integrity of words so the character count may be slightly -more or less then what you specify. Example +more or less then what you specify. -:: +Example:: $string = "Here is a nice text string consisting of eleven words."; $string = character_limiter($string, 20); @@ -46,55 +58,78 @@ more or less then what you specify. Example The third parameter is an optional suffix added to the string, if undeclared this helper uses an ellipsis. -**Note:** If you need to truncate to an exact number of characters please see -the :ref:`ellipsize` function below. +.. note:: If you need to truncate to an exact number of characters please + see the :ref:`ellipsize()` function below. ascii_to_entities() =================== +.. php:function:: ascii_to_entities($str) + + :param string $str: Input string + :returns: string + Converts ASCII values to character entities, including high ASCII and MS Word characters that can cause problems when used in a web page, so that they can be shown consistently regardless of browser settings or stored reliably in a database. There is some dependence on your server's supported character sets, so it may not be 100% reliable in all cases, but for the most part it should correctly identify characters outside -the normal range (like accented characters). Example +the normal range (like accented characters). -:: +Example:: $string = ascii_to_entities($string); entities_to_ascii() =================== -This function does the opposite of the previous one; it turns character -entities back into ASCII. +.. php:function::entities_to_ascii($str, $all = TRUE) + + :param string $str: Input string + :param bool $all: Whether to convert unsafe entities as well + :returns: string + +This function does the opposite of :php:func:`ascii_to_entities()`. +It turns character entities back into ASCII. convert_accented_characters() ============================= -Transliterates high ASCII characters to low ASCII equivalents, useful +.. php:function:: convert_accented_characters($str) + + :param string $str: Input string + :returns: string + +Transliterates high ASCII characters to low ASCII equivalents. Useful when non-English characters need to be used where only standard ASCII characters are safely used, for instance, in URLs. -:: +Example:: $string = convert_accented_characters($string); -This function uses a companion config file -`application/config/foreign_chars.php` to define the to and from array -for transliteration. +.. note:: This function uses a companion config file + `application/config/foreign_chars.php` to define the to and + from array for transliteration. word_censor() ============= +.. php:function:: word_censor($str, $censored, $replacement = '') + + :param string $str: Input string + :param array $censored: List of bad words to censor + :param string $replacement: What to replace bad words with + :returns: string + Enables you to censor words within a text string. The first parameter will contain the original string. The second will contain an array of -words which you disallow. The third (optional) parameter can contain a -replacement value for the words. If not specified they are replaced with -pound signs: ####. Example +words which you disallow. The third (optional) parameter can contain +a replacement value for the words. If not specified they are replaced +with pound signs: ####. -:: +Example:: $disallowed = array('darn', 'shucks', 'golly', 'phooey'); $string = word_censor($string, $disallowed, 'Beep!'); @@ -102,48 +137,76 @@ pound signs: ####. Example highlight_code() ================ +.. php:function:: highlight_code($str) + + :param string $str: Input string + :returns: string + Colorizes a string of code (PHP, HTML, etc.). Example:: $string = highlight_code($string); -The function uses PHP's highlight_string() function, so the colors used -are the ones specified in your php.ini file. +The function uses PHP's ``highlight_string()`` function, so the +colors used are the ones specified in your php.ini file. highlight_phrase() ================== +.. php:function:: highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>') + + :param string $str: Input string + :param string $phrase: Phrase to highlight + :param string $tag_open: Opening tag used for the highlight + :param string $tag_close: Closing tag for the highlight + :returns: string + Will highlight a phrase within a text string. The first parameter will contain the original string, the second will contain the phrase you wish to highlight. The third and fourth parameters will contain the -opening/closing HTML tags you would like the phrase wrapped in. Example +opening/closing HTML tags you would like the phrase wrapped in. -:: +Example:: $string = "Here is a nice text string about nothing in particular."; - $string = highlight_phrase($string, "nice text", '<span style="color:#990000">', '</span>'); + echo highlight_phrase($string, "nice text", '<span style="color:#990000;">', '</span>'); -The above text returns: +The above code prints:: -Here is a nice text string about nothing in particular. + Here is a <span style="color:#990000;">nice text</span> string about nothing in particular. word_wrap() =========== -Wraps text at the specified **character** count while maintaining -complete words. Example +.. php:function:: word_wrap($str, $charlim = 76) + + :param string $str: Input string + :param int $charlim: Character limit + :returns: string -:: +Wraps text at the specified *character* count while maintaining +complete words. + +Example:: $string = "Here is a simple string of text that will help us demonstrate this function."; echo word_wrap($string, 25); // Would produce: Here is a simple string of text that will help us demonstrate this function -.. _ellipsize: +.. _ellipsize(): ellipsize() =========== +.. php:function:: ellipsize($str, $max_length, $position = 1, $ellipsis = '…') + + :param string $str: Input string + :param int $max_length: String length limit + :param mixed $position: Position to split at + (int or float) + :param string $ellipsis: What to use as the ellipsis character + :returns: string + This function will strip tags from a string, split it at a defined maximum length, and insert an ellipsis. @@ -156,14 +219,11 @@ string, .5 in the middle, and 0 at the left. An optional forth parameter is the kind of ellipsis. By default, … will be inserted. -:: +Example:: $str = 'this_string_is_entirely_too_long_and_might_break_my_design.jpg'; echo ellipsize($str, 32, .5); -Produces: - -:: - - this_string_is_e…ak_my_design.jpg +Produces:: + this_string_is_e…ak_my_design.jpg
\ No newline at end of file diff --git a/user_guide_src/source/helpers/typography_helper.rst b/user_guide_src/source/helpers/typography_helper.rst index f3202603a..3c81687ac 100644 --- a/user_guide_src/source/helpers/typography_helper.rst +++ b/user_guide_src/source/helpers/typography_helper.rst @@ -10,9 +10,7 @@ in semantically relevant ways. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('typography'); @@ -21,9 +19,18 @@ The following functions are available: auto_typography() ================= +.. php:function:: auto_typography($str, $reduce_linebreaks = FALSE) + + :param string $str: Input string + :param bool $reduce_linebreaks: Whether to reduce multiple instances of double newlines to two + :returns: string + Formats text so that it is semantically and typographically correct -HTML. Please see the :doc:`Typography Class <../libraries/typography>` -for more info. +HTML. + +This function is an alias for ``CI_Typography::auto_typography``. +For more info, please see the :doc:`Typography Library +<../libraries/typography>` documentation. Usage example:: @@ -31,18 +38,34 @@ Usage example:: .. note:: Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. If you choose to use this - function you may want to consider `caching </general/caching>` your pages. + function you may want to consider `caching <../general/caching>` your + pages. nl2br_except_pre() ================== -Converts newlines to <br /> tags unless they appear within <pre> tags. -This function is identical to the native PHP nl2br() function, except -that it ignores <pre> tags. +.. php:function:: nl2br_except_pre($str) -Usage example + :param string $str: Input string + :returns: string -:: +Converts newlines to <br /> tags unless they appear within <pre> tags. +This function is identical to the native PHP ``nl2br()`` function, +except that it ignores <pre> tags. + +Usage example:: $string = nl2br_except_pre($string); +entity_decode() +=============== + +.. php:function:: entity_decode($str, $charset = NULL) + + :param string $str: Input string + :param string $charset: Character set + :returns: string + +This function is an alias for ``CI_Security::entity_decode()``. +Fore more info, please see the :doc:`Security Library +<../libraries/security>` documentation.
\ No newline at end of file diff --git a/user_guide_src/source/helpers/url_helper.rst b/user_guide_src/source/helpers/url_helper.rst index 1987dfb72..5b8fa5f44 100644 --- a/user_guide_src/source/helpers/url_helper.rst +++ b/user_guide_src/source/helpers/url_helper.rst @@ -9,9 +9,7 @@ The URL Helper file contains functions that assist in working with URLs. Loading this Helper =================== -This helper is loaded using the following code - -:: +This helper is loaded using the following code:: $this->load->helper('url'); @@ -20,119 +18,135 @@ The following functions are available: site_url() ========== +.. php:function:: site_url($uri = '') + + :param string $uri: URI string + :returns: string + Returns your site URL, as specified in your config file. The index.php -file (or whatever you have set as your site index_page in your config +file (or whatever you have set as your site **index_page** in your config file) will be added to the URL, as will any URI segments you pass to the -function, and the url_suffix as set in your config file. +function, plus the **url_suffix** as set in your config file. You are encouraged to use this function any time you need to generate a local URL so that your pages become more portable in the event your URL changes. Segments can be optionally passed to the function as a string or an -array. Here is a string example +array. Here is a string example:: -:: - - echo site_url("news/local/123"); + echo site_url('news/local/123'); The above example would return something like: -http://example.com/index.php/news/local/123 - -Here is an example of segments passed as an array +*http://example.com/index.php/news/local/123* -:: +Here is an example of segments passed as an array:: $segments = array('news', 'local', '123'); echo site_url($segments); +This function is an alias for ``CI_Config::site_url()``. For more info, +please see the :doc:`Config Library <../libraries/config>` documentation. + base_url() =========== -Returns your site base URL, as specified in your config file. Example +.. php:function:: base_url($uri = '') -:: + :param string $uri: URI string + :returns: string - echo base_url(); +Returns your site base URL, as specified in your config file. Example:: -This function returns the same thing as `site_url`, without the -index_page or url_suffix being appended. + echo base_url(); -Also like site_url, you can supply segments as a string or an array. -Here is a string example +This function returns the same thing as :php:func:`site_url()`, without +the *index_page* or *url_suffix* being appended. -:: +Also like :php:func:`site_url()`, you can supply segments as a string or +an array. Here is a string example:: echo base_url("blog/post/123"); The above example would return something like: -http://example.com/blog/post/123 - -This is useful because unlike `site_url()`, you can supply a string to a -file, such as an image or stylesheet. For example +*http://example.com/blog/post/123* -:: +This is useful because unlike :php:func:`site_url()`, you can supply a +string to a file, such as an image or stylesheet. For example:: echo base_url("images/icons/edit.png"); This would give you something like: -http://example.com/images/icons/edit.png +*http://example.com/images/icons/edit.png* + +This function is an alias for ``CI_Config::base_url()``. For more info, +please see the :doc:`Config Library <../libraries/config>` documentation. current_url() ============= +.. php:function:: current_url() + + :returns: string + Returns the full URL (including segments) of the page being currently viewed. +.. note:: Calling this function is the same as doing this: + | + | site_url(uri_string()); + uri_string() ============ -Returns the URI segments of any page that contains this function. For -example, if your URL was this +.. php:function:: uri_string() -:: + :returns: string - http://some-site.com/blog/comments/123 +Returns the URI segments of any page that contains this function. +For example, if your URL was this:: -The function would return + http://some-site.com/blog/comments/123 -:: +The function would return:: /blog/comments/123 +This function is an alias for ``CI_Config::uri_string()``. For more info, +please see the :doc:`Config Library <../libraries/config>` documentation. + index_page() ============ -Returns your site "index" page, as specified in your config file. -Example +.. php:function:: index_page() + + :returns: string -:: +Returns your site **index_page**, as specified in your config file. +Example:: echo index_page(); anchor() ======== -Creates a standard HTML anchor link based on your local site URL - -:: +.. php:function:: anchor($uri = '', $title = '', $attributes = '') - <a href="http://example.com">Click Here</a> + :param string $uri: URI string + :param string $title: Anchor title + :param mixed $attributes: HTML attributes + :returns: string -The tag has three optional parameters - -:: - - anchor(uri segments, text, attributes) +Creates a standard HTML anchor link based on your local site URL. The first parameter can contain any segments you wish appended to the -URL. As with the site_url() function above, segments can be a string or -an array. +URL. As with the :php:func:`site_url()` function above, segments can +be a string or an array. .. note:: If you are building links that are internal to your application - do not include the base URL (http://...). This will be added automatically - from the information specified in your config file. Include only the - URI segments you wish appended to the URL. + do not include the base URL (http://...). This will be added + automatically from the information specified in your config file. + Include only the URI segments you wish appended to the URL. The second segment is the text you would like the link to say. If you leave it blank, the URL will be used. @@ -141,41 +155,43 @@ The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple string or an associative array. -Here are some examples - -:: +Here are some examples:: echo anchor('news/local/123', 'My News', 'title="News title"'); - -Would produce: <a href="http://example.com/index.php/news/local/123" -title="News title">My News</a> - -:: + // Prints: <a href="http://example.com/index.php/news/local/123" title="News title">My News</a> echo anchor('news/local/123', 'My News', array('title' => 'The best news!')); + // Prints: <a href="http://example.com/index.php/news/local/123" title="The best news!">My News</a> -Would produce: <a href="http://example.com/index.php/news/local/123" -title="The best news!">My News</a> + echo anchor('', 'Click here'); + // Prints: <a href="http://example.com">Click Here</a> anchor_popup() ============== -Nearly identical to the anchor() function except that it opens the URL -in a new window. You can specify JavaScript window attributes in the -third parameter to control how the window is opened. If the third -parameter is not set it will simply open a new window with your own -browser settings. Here is an example with attributes +.. php:function:: anchor_popup($uri = '', $title = '', $attributes = FALSE) -:: + :param string $uri: URI string + :param string $title: Anchor title + :param mixed $attributes: HTML attributes + :returns: string + +Nearly identical to the :php:func:``anchor()`` function except that it +opens the URL in a new window. You can specify JavaScript window +attributes in the third parameter to control how the window is opened. +If the third parameter is not set it will simply open a new window with +your own browser settings. + +Here is an example with attributes:: $atts = array( - 'width' => '800', - 'height' => '600', + 'width' => 800, + 'height' => 600, 'scrollbars' => 'yes', 'status' => 'yes', 'resizable' => 'yes', - 'screenx' => '0', - 'screeny' => '0', + 'screenx' => 0, + 'screeny' => 0, 'window_name' => '_blank' ); @@ -184,13 +200,11 @@ browser settings. Here is an example with attributes .. note:: The above attributes are the function defaults so you only need to set the ones that are different from what you need. If you want the function to use all of its defaults simply pass an empty array in the - third parameter - -:: + third parameter: + | + | echo anchor_popup('news/local/123', 'Click Me!', array()); - echo anchor_popup('news/local/123', 'Click Me!', array()); - -.. note:: The 'window_name' is not really an attribute, but an argument to +.. note:: The **window_name** is not really an attribute, but an argument to the JavaScript `window.open() <http://www.w3schools.com/jsref/met_win_open.asp>` method, which accepts either a window name or a window target. @@ -200,117 +214,149 @@ browser settings. Here is an example with attributes mailto() ======== -Creates a standard HTML email link. Usage example +.. php:function:: mailto($email, $title = '', $attributes = '') -:: + :param string $email: E-mail address + :param string $title: Anchor title + :param mixed $attributes: HTML attributes + :returns: string - echo mailto('me@my-site.com', 'Click Here to Contact Me'); +Creates a standard HTML e-mail link. Usage example:: -As with the anchor() tab above, you can set attributes using the third -parameter: + echo mailto('me@my-site.com', 'Click Here to Contact Me'); -:: +As with the :php:func:`anchor()` tab above, you can set attributes using the +third parameter:: - $attributes = array('title' => 'Mail me'); - echo mailto('me@my-site.com', 'Contact Me', $attributes); + $attributes = array('title' => 'Mail me'); + echo mailto('me@my-site.com', 'Contact Me', $attributes); safe_mailto() ============= -Identical to the above function except it writes an obfuscated version -of the mailto tag using ordinal numbers written with JavaScript to help -prevent the email address from being harvested by spam bots. +.. php:function:: safe_mailto($email, $title = '', $attributes = '') + + :param string $email: E-mail address + :param string $title: Anchor title + :param mixed $attributes: HTML attributes + :returns: string + +Identical to the :php:func:`mailto()` function except it writes an obfuscated +version of the *mailto* tag using ordinal numbers written with JavaScript to +help prevent the e-mail address from being harvested by spam bots. auto_link() =========== -Automatically turns URLs and email addresses contained in a string into -links. Example +.. php:function:: auto_link($str, $type = 'both', $popup = FALSE) + + :param string $str: Input string + :param string $type: Link type ('email', 'url' or 'both') + :param bool $popup: Whether to create popup links + :returns: string -:: +Automatically turns URLs and e-mail addresses contained in a string into +links. Example:: $string = auto_link($string); -The second parameter determines whether URLs and emails are converted or +The second parameter determines whether URLs and e-mails are converted or just one or the other. Default behavior is both if the parameter is not -specified. Email links are encoded as safe_mailto() as shown above. +specified. E-mail links are encoded as :php:func:`safe_mailto()` as shown +above. -Converts only URLs - -:: +Converts only URLs:: $string = auto_link($string, 'url'); -Converts only Email addresses - -:: +Converts only e-mail addresses:: $string = auto_link($string, 'email'); The third parameter determines whether links are shown in a new window. -The value can be TRUE or FALSE (boolean) - -:: +The value can be TRUE or FALSE (boolean):: $string = auto_link($string, 'both', TRUE); url_title() =========== +.. php:function:: url_title($str, $separator = '-', $lowercase = FALSE) + + :param string $str: Input string + :param string $separator: Word separator + :param string $lowercase: Whether to transform the output string to lower-case + :returns: string + Takes a string as input and creates a human-friendly URL string. This is useful if, for example, you have a blog in which you'd like to use the -title of your entries in the URL. Example - -:: +title of your entries in the URL. Example:: $title = "What's wrong with CSS?"; - $url_title = url_title($title); // Produces: Whats-wrong-with-CSS + $url_title = url_title($title); + // Produces: Whats-wrong-with-CSS The second parameter determines the word delimiter. By default dashes -are used. Options are: dash, or underscore +are used. Preferred options are: **-** (dash) or **_** (underscore) -:: +Example:: $title = "What's wrong with CSS?"; - $url_title = url_title($title, 'underscore'); // Produces: Whats_wrong_with_CSS + $url_title = url_title($title, 'underscore'); + // Produces: Whats_wrong_with_CSS + +.. note:: Old usage of 'dash' and 'underscore' as the second parameter + is DEPRECATED. The third parameter determines whether or not lowercase characters are -forced. By default they are not. Options are boolean TRUE/FALSE +forced. By default they are not. Options are boolean TRUE/FALSE. -:: +Example:: $title = "What's wrong with CSS?"; - $url_title = url_title($title, 'underscore', TRUE); // Produces: whats_wrong_with_css + $url_title = url_title($title, 'underscore', TRUE); + // Produces: whats_wrong_with_css prep_url() ---------- -This function will add http:// in the event that a scheme is missing -from a URL. Pass the URL string to the function like this +.. php:function:: prep_url($str = '') + + :param string $str: URL string + :returns: string -:: +This function will add http:// in the event that a protocol prefix +is missing from a URL. - $url = "example.com"; - $url = prep_url($url); +Pass the URL string to the function like this:: + + $url = prep_url('example.com'); redirect() ========== +.. php:function:: redirect($uri = '', $method = 'auto', $code = NULL) + + :param string $uri: URI string + :param string $method: Redirect method ('auto', 'location' or 'refresh') + :param string $code: HTTP Response code (usually 302 or 303) + :returns: void + Does a "header redirect" to the URI specified. If you specify the full site URL that link will be built, but for local links simply providing the URI segments to the controller you want to direct to will create the link. The function will build the URL based on your config file values. The optional second parameter allows you to force a particular redirection -method. The available methods are "location" or "refresh", with location -being faster but less reliable on IIS servers. The default is "auto", -which will attempt to intelligently choose the method based on the server -environment. +method. The available methods are **auto**, **location** and **refresh**, +with location being faster but less reliable on IIS servers. +The default is **auto**, which will attempt to intelligently choose the +method based on the server environment. The optional third parameter allows you to send a specific HTTP Response Code - this could be used for example to create 301 redirects for search engine purposes. The default Response Code is 302. The third parameter is -*only* available with 'location' redirects, and not 'refresh'. Examples:: +*only* available with **location** redirects, and not *refresh*. Examples:: if ($logged_in == FALSE) { @@ -324,8 +370,14 @@ engine purposes. The default Response Code is 302. The third parameter is is outputted to the browser since it utilizes server headers. .. note:: For very fine grained control over headers, you should use the - `Output Library </libraries/output>` set_header() function. + `Output Library </libraries/output>` ``set_header()`` method. -.. note:: To IIS users: if you hide the `Server` HTTP header, the "auto" +.. note:: To IIS users: if you hide the `Server` HTTP header, the *auto* method won't detect IIS, in that case it is advised you explicitly - use the "refresh" method. + use the **refresh** method. + +.. note:: When the **location** method is used, an HTTP status code of 303 + will *automatically* be selected when the page is currently accessed + via POST and HTTP/1.1 is used. + +.. important:: This function will terminate script execution.
\ No newline at end of file diff --git a/user_guide_src/source/installation/upgrade_211.rst b/user_guide_src/source/installation/upgrade_211.rst index 59faca8e6..f0e70f6dc 100644 --- a/user_guide_src/source/installation/upgrade_211.rst +++ b/user_guide_src/source/installation/upgrade_211.rst @@ -8,9 +8,7 @@ replacing the index.php file with a static one. Step 1: Update your CodeIgniter files ===================================== -Replace all files and directories in your "system" folder and replace -your index.php file. If any modifications were made to your index.php -they will need to be made fresh in this new one. +Replace all files and directories in your "system" folder. .. note:: If you have any custom developed files in these folders please make copies of them first. diff --git a/user_guide_src/source/installation/upgrade_212.rst b/user_guide_src/source/installation/upgrade_212.rst index 205ad8622..4b76482e3 100644 --- a/user_guide_src/source/installation/upgrade_212.rst +++ b/user_guide_src/source/installation/upgrade_212.rst @@ -8,9 +8,7 @@ replacing the index.php file with a static one. Step 1: Update your CodeIgniter files ===================================== -Replace all files and directories in your "system" folder and replace -your index.php file. If any modifications were made to your index.php -they will need to be made fresh in this new one. +Replace all files and directories in your "system" folder. .. note:: If you have any custom developed files in these folders please make copies of them first. diff --git a/user_guide_src/source/installation/upgrade_213.rst b/user_guide_src/source/installation/upgrade_213.rst new file mode 100644 index 000000000..3a3497ccb --- /dev/null +++ b/user_guide_src/source/installation/upgrade_213.rst @@ -0,0 +1,20 @@ +############################# +Upgrading from 2.1.2 to 2.1.3 +############################# + +Before performing an update you should take your site offline by +replacing the index.php file with a static one. + +Step 1: Update your CodeIgniter files +===================================== + +Replace all files and directories in your "system" folder. + +.. note:: If you have any custom developed files in these folders please + make copies of them first. + +Step 2: Update your user guide +============================== + +Please also replace your local copy of the user guide with the new +version.
\ No newline at end of file diff --git a/user_guide_src/source/installation/upgrade_300.rst b/user_guide_src/source/installation/upgrade_300.rst index 6d99f4655..0af21b11e 100644 --- a/user_guide_src/source/installation/upgrade_300.rst +++ b/user_guide_src/source/installation/upgrade_300.rst @@ -31,8 +31,19 @@ Step 3: Remove $autoload['core'] from your config/autoload.php Use of the ``$autoload['core']`` config array has been deprecated as of CodeIgniter 1.4.1 and is now removed. Move any entries that you might have listed there to ``$autoload['libraries']`` instead. +*************************************************** +Step 4: Move your Log class overrides or extensions +*************************************************** + +The Log Class is considered as a "core" class and is now located in the +**system/core/** directory. Therefore, in order for your Log class overrides +or extensions to work, you need to move them to **application/core/**:: + + application/libraries/Log.php -> application/core/Log.php + application/libraries/MY_Log.php -> application/core/MY_log.php + ************************************************************** -Step 4: Add new session driver items to your config/config.php +Step 5: Add new session driver items to your config/config.php ************************************************************** With the change from a single Session Library to the new Session Driver, two new config items have been added: @@ -48,7 +59,7 @@ available as valid drivers, neither of these configuration items are required. H add them for clarity and ease of configuration in the future. *************************************** -Step 5: Update your config/database.php +Step 6: Update your config/database.php *************************************** Due to 3.0.0's renaming of Active Record to Query Builder, inside your `config/database.php`, you will @@ -60,13 +71,13 @@ need to rename the `$active_record` variable to `$query_builder` $query_builder = TRUE; ******************************* -Step 6: Move your errors folder +Step 7: Move your errors folder ******************************* In version 3.0.0, the errors folder has been moved from _application/errors* to _application/views/errors*. ******************************************************* -Step 7: Update your config/routes.php containing (:any) +Step 8: Update your config/routes.php containing (:any) ******************************************************* Historically, CodeIgniter has always provided the **:any** wildcard in routing, @@ -87,15 +98,37 @@ regular expression:: **************************************************************************** -Step 8: Check the calls to Array Helper's element() and elements() functions +Step 9: Check the calls to Array Helper's element() and elements() functions **************************************************************************** The default return value of these functions, when the required elements don't exist, has been changed from FALSE to NULL. -********************************************************** -Step 9: Change usage of Email library with multiple emails -********************************************************** +************************************************************* +Step 10: Update usage of Database Forge's drop_table() method +************************************************************* + +Up until now, ``drop_table()`` added an IF EXISTS clause by default or it didn't work +at all with some drivers. In CodeIgniter 3.0, the IF EXISTS condition is no longer added +by default and has an optional second parameter that allows that instead and is set to +FALSE by default. + +If your application relies on IF EXISTS, you'll have to change its usage. + +:: + + // Now produces just DROP TABLE `table_name` + $this->dbforge->drop_table('table_name'); + + // Produces DROP TABLE IF EXISTS `table_name` + $this->dbforge->drop_table('table_name', TRUE); + +.. note:: The given example users MySQL-specific syntax, but it should work across + all drivers with the exception of ODBC. + +*********************************************************** +Step 11: Change usage of Email library with multiple emails +*********************************************************** The :doc:`Email library <../libraries/email>` will automatically clear the set parameters after successfully sending emails. To override this behaviour, @@ -110,7 +143,7 @@ pass FALSE as the first parameter in the ``send()`` method: **************************************************************** -Step 10: Remove usage of (previously) deprecated functionalities +Step 12: Remove usage of (previously) deprecated functionalities **************************************************************** In addition to the ``$autoload['core']`` configuration setting, there's a number of other functionalities @@ -159,23 +192,37 @@ CodeIgniter 3.1+. String helper repeater() ======================== -:doc:`String Helper <../helpers/string_helper>` function ``repeater()`` is now just an alias for -PHP's native ``str_repeat()`` function. It is deprecated and scheduled for removal in -CodeIgniter 3.1+. +:doc:`String Helper <../helpers/string_helper>` function :php:func:`repeater()` is now just an alias for +PHP's native ``str_repeat()`` function. It is deprecated and scheduled for removal in CodeIgniter 3.1+. .. note:: This function is still available, but you're strongly encouraged to remove it's usage sooner rather than later. -Form helper form_prep() -======================= +String helper trim_slashes() +============================ -:doc:`Form Helper <../helpers/form_helper>` function ``form_prep()`` is now just an alias for -:doc:`common function <../general/common_functions>` ``html_escape()`` and it's second argument -is ignored. It is deprecated and scheduled for removal in CodeIgniter 3.1+. +:doc:`String Helper <../helpers/string_helper>` function :php:func:`trim_slashes()` is now just an alias +for PHP's native ``trim()`` function (with a slash passed as its second argument). It is deprecated and +scheduled for removal in CodeIgniter 3.1+. .. note:: This function is still available, but you're strongly encouraged to remove it's usage sooner rather than later. +Email helper functions +====================== + +:doc:`Email Helper <../helpers/email_helper>` only has two functions + + - :php:func:`valid_email()` + - :php:func:`send_email()` + +Both of them are now aliases for PHP's native ``filter_var()`` and ``mail()`` functions, respectively. +Therefore the :doc:`Email Helper <../helpers/email_helper>` altogether is being deprecated and +is scheduled for removal in CodeIgniter 3.1+. + +.. note:: These functions are still available, but you're strongly encouraged to remove their usage + sooner rather than later. + Date helper standard_date() =========================== @@ -212,4 +259,59 @@ As a result of that, the 'anchor_class' setting is now deprecated and scheduled CodeIgniter 3.1+. .. note:: This setting is still available, but you're strongly encouraged to remove its' usage sooner - rather than later.
\ No newline at end of file + rather than later. + +String helper random_string() types 'unique' and 'encrypt' +========================================================== + +When using the :doc:`String Helper <helpers/string_helper>` function :php:func:`random_string()`, +you should no longer pass the **unique** and **encrypt** randomization types. They are only +aliases for **md5** and **sha1** respectively and are now deprecated and scheduled for removal +in CodeIgniter 3.1+. + +.. note:: These options are still available, but you're strongly encouraged to remove their usage + sooner rather than later. + +URL helper url_title() separators 'dash' and 'underscore' +========================================================= + +When using the :doc:`URL Helper <helpers/url_helper>` function :php:func:`url_title()`, you +should no longer pass **dash** or **underscore** as the word separator. This function will +now accept any character and you should just pass the chosen character directly, so you +should write '-' instead of 'dash' and '_' instead of 'underscore'. + +**dash** and **underscore** now act as aliases and are deprecated and scheduled for removal +in CodeIgniter 3.1+. + +.. note:: These options are still available, but you're strongly encouraged to remove their usage + sooner rather than later. + +Database Forge method add_column() with an AFTER clause +======================================================= + +If you have used the **third parameter** for :doc:`Database Forge <database/forge>` method +``add_column()`` to add a field for an AFTER clause, then you should change its usage. + +That third parameter has been deprecated and scheduled for removal in CodeIgniter 3.1+. + +You should now put AFTER clause field names in the field definition array instead:: + + // Old usage: + $field = array( + 'new_field' => array('type' => 'TEXT') + ); + + $this->dbforge->add_column('table_name', $field, 'another_field'); + + // New usage: + $field = array( + 'new_field' => array('type' => 'TEXT', 'after' => 'another_field') + ); + + $this->dbforge->add_column('table_name', $field); + +.. note:: The parameter is still available, but you're strongly encouraged to remove its usage + sooner rather than later. + +.. note:: This is for MySQL and CUBRID databases only! Other drivers don't support this + clause and will silently ignore it. diff --git a/user_guide_src/source/installation/upgrading.rst b/user_guide_src/source/installation/upgrading.rst index 545f344ee..4f276207c 100644 --- a/user_guide_src/source/installation/upgrading.rst +++ b/user_guide_src/source/installation/upgrading.rst @@ -5,7 +5,8 @@ Upgrading From a Previous Version Please read the upgrade notes corresponding to the version you are upgrading from. -- :doc:`Upgrading from 2.1.2 to 3.0.0 <upgrade_300>` +- :doc:`Upgrading from 2.1.3 to 3.0.0 <upgrade_300>` +- :doc:`Upgrading from 2.1.2 to 2.1.3 <upgrade_213>` - :doc:`Upgrading from 2.1.1 to 2.1.2 <upgrade_212>` - :doc:`Upgrading from 2.1.0 to 2.1.1 <upgrade_211>` - :doc:`Upgrading from 2.0.3 to 2.1.0 <upgrade_210>` diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst index 4d1940212..a3a35b499 100644 --- a/user_guide_src/source/libraries/form_validation.rst +++ b/user_guide_src/source/libraries/form_validation.rst @@ -288,8 +288,8 @@ 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: @@ -315,8 +315,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 @@ -910,9 +910,6 @@ Rule Parameter Description to two parameters, where at least one is required (to pass the field data). -.. note:: When using the **matches** rule, the form item specified - to compare against must already be defined. - ****************** Prepping Reference ****************** diff --git a/user_guide_src/source/libraries/input.rst b/user_guide_src/source/libraries/input.rst index c0b9c6589..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,7 +13,7 @@ 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: @@ -47,7 +46,7 @@ Using POST, GET, COOKIE, or SERVER Data 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']) +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 @@ -55,7 +54,7 @@ you might do something like this:: $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'); @@ -74,7 +73,7 @@ looking for:: $this->input->post('some_data'); -The function returns NULL if the item you are attempting to retrieve +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 @@ -89,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 NULL if there are no items in the POST. +The method returns NULL if there are no items in the POST. :: @@ -99,8 +98,8 @@ The function returns NULL 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); @@ -109,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 NULL if there are no items in the GET. +The method returns NULL if there are no items in the GET. :: @@ -118,9 +117,9 @@ The function returns NULL 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); @@ -128,8 +127,8 @@ 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 @@ -138,16 +137,43 @@ data:: $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 @@ -182,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. @@ -198,22 +224,25 @@ parameters:: $this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); + $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. :: @@ -230,7 +259,7 @@ 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. @@ -243,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>`_ @@ -253,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. @@ -263,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. @@ -278,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). @@ -287,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/sessions.rst b/user_guide_src/source/libraries/sessions.rst index dd9e8cbb4..ee7fb0b1c 100644 --- a/user_guide_src/source/libraries/sessions.rst +++ b/user_guide_src/source/libraries/sessions.rst @@ -388,7 +388,7 @@ session class:: 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`) ); 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 |