diff options
Diffstat (limited to 'user_guide_src/source')
94 files changed, 4363 insertions, 2462 deletions
diff --git a/user_guide_src/source/_themes/eldocs/layout.html b/user_guide_src/source/_themes/eldocs/layout.html index 01db07cac..51d61b849 100644 --- a/user_guide_src/source/_themes/eldocs/layout.html +++ b/user_guide_src/source/_themes/eldocs/layout.html @@ -91,13 +91,7 @@ </div><!-- /#brand --> <div id="header"> - <form method="get" action="http://www.google.com/search"> - <fieldset> - <input type="text" name="q" id="q" value=""> - <input type="hidden" name="as_sitesearch" id="as_sitesearch" value="{{ project_domain }}/user_guide/" /> - <input class="grades" type="submit" value="search"> - </fieldset> - </form> + {%- include "searchbox.html" %} <ul> {%- block rootrellink %} <li><a href="{{ pathto(master_doc) }}">User Guide Home</a>{%- if pagename != 'index' %} {{ reldelim1 }}{%- endif %}</li> @@ -113,8 +107,10 @@ </ul> </div><!-- /#header --> - <div class="section" id="content"> + <div class="section body" id="content"> + {%- block body %} {{ body }} + {%- endblock %} </div> {%- endblock %} @@ -125,8 +121,8 @@ {%- block footer %} <div id="footer"> <p class="top"><a href="#header" title="Return to top">Return to top</a></p> - <p><a href="{{ project_url }}">{{ project }}</a> – Copyright © {{ copyright }}</a></p> + <p><a href="http://{{ project_domain }}/">{{ project }}</a> – Copyright © {{ copyright }}</a></p> </div><!-- /#footer --> {%- endblock %} </body> -</html> +</html>
\ No newline at end of file diff --git a/user_guide_src/source/_themes/eldocs/searchbox.html b/user_guide_src/source/_themes/eldocs/searchbox.html new file mode 100644 index 000000000..039590bd9 --- /dev/null +++ b/user_guide_src/source/_themes/eldocs/searchbox.html @@ -0,0 +1,21 @@ +<!-- + -------------------------------- + Original Google search box block + -------------------------------- + +<form method="get" action="http://www.google.com/search"> + <fieldset> + <input type="text" name="q" id="q" value=""> + <input type="hidden" name="as_sitesearch" id="as_sitesearch" value="{{ project_domain }}/user_guide/" /> + <input class="grades" type="submit" value="search"> + </fieldset> +</form> +--> + + +<form class="search" action="{{ pathto('search') }}" method="get"> + <input type="text" name="q" id="q" value="" /> + <input type="submit" value="search" /> + <input type="hidden" name="check_keywords" value="yes" /> + <input type="hidden" name="area" value="default" /> +</form> diff --git a/user_guide_src/source/_themes/eldocs/static/asset/css/common.css b/user_guide_src/source/_themes/eldocs/static/asset/css/common.css index 6cabda037..0a63871c5 100644 --- a/user_guide_src/source/_themes/eldocs/static/asset/css/common.css +++ b/user_guide_src/source/_themes/eldocs/static/asset/css/common.css @@ -148,6 +148,8 @@ fieldset{ border: 0; } .top{ float: right; } +.highlight{ overflow-x: auto; } + .admonition, .highlight-ee, .highlight-ci, @@ -166,6 +168,8 @@ fieldset{ border: 0; } padding: 10px 10px 8px; } +.highlight-ci{ background-color: #FEFEFE; border-color: #E5E5E5; } + .admonition p{ margin: 0; } .codeblock{ margin: 10px 0; } @@ -181,6 +185,8 @@ fieldset{ border: 0; } } .admonition-title:after{ content: ': '; } + +.highlighted{ background-color: #FFF09B; } #table-contents{ bottom: 0; diff --git a/user_guide_src/source/changelog.rst b/user_guide_src/source/changelog.rst index 75229f91f..a3d29056e 100644 --- a/user_guide_src/source/changelog.rst +++ b/user_guide_src/source/changelog.rst @@ -22,33 +22,40 @@ Release Date: Not Released - ``$_SERVER['CI_ENV']`` can now be set to control the ``ENVIRONMENT`` constant. - Added an optional backtrace to php-error template. - Added Android to the list of user agents. - - Added Windows 7, Android, Blackberry and iOS to the list of user platforms. + - Added Windows 7, Windows 8, Android, Blackberry, iOS and PlayStation 3 to the list of user platforms. - Added Fennec (Firefox for mobile) to the list of mobile user agents. - Ability to log certain error types, not all under a threshold. - Added support for pem, p10, p12, p7a, p7c, p7m, p7r, p7s, crt, crl, der, kdb, rsa, cer, sst, csr Certs to mimes.php. - - Added support for pgp and gpg to mimes.php. + - Added support for pgp, gpg, zsh and cdr files to mimes.php. - Added support for 3gp, 3g2, mp4, wmv, f4v, vlc Video files to mimes.php. - - Added support for m4a, aac, m4u, xspf, au, ac3, flac, ogg Audio files to mimes.php. + - Added support for m4a, aac, m4u, xspf, au, ac3, flac, ogg, wma Audio files to mimes.php. - Added support for kmz and kml (Google Earth) files to mimes.php. - Added support for ics Calendar files to mimes.php. - - Added support for rar archives to mimes.php. + - Added support for rar, jar and 7zip archives to mimes.php. - Updated support for xml ('application/xml') and xsl ('application/xml', 'text/xsl') files in mimes.php. - Updated support for doc files in mimes.php. + - Updated support for docx files in mimes.php. - Updated support for php files in mimes.php. - Updated support for zip files in mimes.php. + - Updated support for csv files in mimes.php. - Added some more doctypes. - - Added Romanian and Greek characters in foreign_characters.php. + - Added Romanian, Greek, Vietnamese and Cyrilic characters in *application/config/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. - - Updated email validation methods to use filter_var() instead of PCRE. + - Updated email validation methods to use ``filter_var()`` instead of PCRE. + - 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 @@ -56,150 +63,262 @@ Release Date: Not Released - ``now()`` now works with all timezone strings supported by PHP. - Added an optional third parameter to ``timespan()`` that constrains the number of time units displayed. - Added an optional parameter to ``timezone_menu()`` that allows more attributes to be added to the generated select tag. - - Deprecated ``standard_date()``, which now just uses the native ``date()`` with `DateTime constants <http://bg2.php.net/manual/en/class.datetime.php#datetime.constants.types>`_. + - Deprecated ``standard_date()``, which now just uses the native ``date()`` with `DateTime constants <http://www.php.net/manual/en/class.datetime.php#datetime.constants.types>`_. + - 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()``. + - 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). + - Changed :php:func:`anchor()`, :php:func:`anchor_popup()`, and :php:func:`redirect()` to support protocol-relative URLs (e.g. *//ellislab.com/codeigniter*). - 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. - - 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. - - ``form_dropdown()`` will now also take an array for unity with other form helpers. - - ``do_hash()`` now uses PHP's native ``hash()`` function (supporting more algorithms) and is deprecated. - - Removed previously deprecated helper function ``js_insert_smiley()`` from smiley helper. + - :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. + - :doc:`Download Helper <helpers/download_helper>` changes include: + - Added an optional third parameter to :php:func:`force_download()` that enables/disables sending the actual file MIME type in the Content-Type header (disabled by default). + - Added a work-around in :php:func:`force_download()` for a bug Android <= 2.1, where the filename extension needs to be in uppercase. + - Added support for reading from an existing file path by passing NULL as the second parameter to :php:func:`force_download()` (useful for large files and/or safely transmitting binary data). + - :doc:`Form Helper <helpers/form_helper>` changes include: + - :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>`. + - :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>` :php:func:`directory_map()` will now append ``DIRECTORY_SEPARATOR`` to directory names in the returned array. + - :doc:`Language Helper <helpers/language_helper>` :php:func:`lang()` now accepts an optional list of additional HTML attributes. + - 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()``. + - 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 capability for packages to hold *config/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 support for join() with multiple conditions. - - Added support for USING in join(). - - Changed limit() to ignore NULL values instead of always casting to integer. - - Changed offset() to ignore empty values instead of always casting to integer. + - 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()``, ``insert()``, ``insert_batch()``. + - Added support for ``join()`` with multiple conditions. + - Added support for *USING* in ``join()``. + - Added seed values support for random ordering with ``order_by(seed, 'RANDOM')``. + - Changed ``limit()`` to ignore NULL values instead of always casting to integer. + - Changed ``offset()`` to ignore empty values instead of always casting to integer. + - Methods ``insert_batch()`` and ``update_batch()`` now return an integer representing the number of rows affected by them. + - :doc:`Database Results <database/results>` changes include: + - 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. + - Added method ``unbuffered_row()`` for fetching a row without prefetching the whole result (consume less memory). + - Renamed former method ``_data_seek()`` to ``data_seek()`` and made it public. - Improved support for the MySQLi driver, including: - OOP style of the PHP extension is now used, instead of the procedural aliases. - 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). - - 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(), that 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 support for ``backup()`` in :doc:`Database Utilities <database/utilities>`. + - 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. - - Added support for optimize_table() in :doc:`Database Utilities <database/utilities>` (rebuilds table indexes). - - Added boolean data type support in escape(). - - Added update_batch() support. - - Removed limit() and order_by() support for UPDATE and DELETE queries in as PostgreSQL does not support those features. - - 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. + - ``pg_version()`` is now used to get the database version number, when possible. + - Added ``db_set_charset()`` support. + - Added support for ``optimize_table()`` in :doc:`Database Utilities <database/utilities>` (rebuilds table indexes). + - Added boolean data type support in ``escape()``. + - 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. + - Changed ``db_connect()`` to include the (new) **schema** value into Postgre's **search_path** session variable. - Improved support of the CUBRID driver, including: - Added DSN string support. - Added persistent connections support. - - Improved list_databases() in :doc:`Database Utility <database/utilities>` (until now only the currently used database was returned). + - Improved ``list_databases()`` in :doc:`Database Utility <database/utilities>` (until now only the currently used database was returned). - Improved support of the MSSQL and SQLSRV drivers, including: - Added random ordering support. - - Added support for optimize_table() in :doc:`Database Utility <database/utilities>`. - - Added escaping with QUOTE_IDENTIFIER setting detection. + - Added support for ``optimize_table()`` in :doc:`Database Utility <database/utilities>`. + - Added escaping with *QUOTE_IDENTIFIER* setting detection. - Added port handling support for UNIX-based systems (MSSQL driver). - - Added OFFSET support for SQL Server 2005 and above. + - Added *OFFSET* support for SQL Server 2005 and above. + - Added ``db_set_charset()`` support (MSSQL driver). - Improved support of the Oracle (OCI8) driver, including: - Added DSN string support (Easy Connect and TNS). - - Added support for drop_table() in :doc:`Database Forge <database/forge>`. - - Added support for list_databases() in :doc:`Database Utilities <database/utilities>`. + - Added support for ``drop_table()`` in :doc:`Database Forge <database/forge>`. + - Added support for ``list_databases()`` in :doc:`Database Utilities <database/utilities>`. - Generally improved for speed and cleaned up all of its components. - - num_rows() is now only called explicitly by the developer and no longer re-executes statements. + - ``num_rows()`` is now only called explicitly by the developer and no longer re-executes statements. - 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 support for ``replace()`` in :doc:`Query Builder <database/query_builder>`. + - Added support for ``drop_table()`` in :doc:`Database Forge <database/forge>`. + - :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 - - CI_Session now respects php.ini's session.gc_probability and session.gc_divisor - - Added max_filename_increment config setting for Upload library. - - CI_Loader::_ci_autoloader() is now a protected method. - - Added custom filename to Email::attach() as $this->email->attach($filename, $disposition, $newname). - - Added possibility to send attachment as buffer string in Email::attach() as $this->email->attach($buffer, $disposition, $newname, $mime). + - :doc:`Session Library <libraries/sessions>` changes include: + - Library changed to :doc:`Driver <general/drivers>` with classic Cookie driver as default. + - Added Native PHP Session driver to work with ``$_SESSION``. + - Custom drivers can be added anywhere in package paths and be loaded with the library. + - Drivers interchangeable on the fly. + - New **tempdata** feature allows setting user data items with an expiration time. + - Added default ``$config['sess_driver']`` and ``$config['sess_valid_drivers']`` items to *config.php* file. + - Cookie driver now respects php.ini's *session.gc_probability* and *session.gc_divisor* settings. + - Cookie driver now uses HMAC authentication instead of the simple md5 checksum. + - The Cookie driver now also checks authentication on encrypted session data. + - Changed the Cookie driver to select only one row when using database sessions. + - Cookie driver now only writes to database at end of request when using database. + - Cookie driver now uses PHP functions for faster array manipulation when using database. + - Added ``all_flashdata()`` method to session class. Returns an associative array of only flashdata. + - Added ``has_userdata()`` method to verify existence of userdata item. + - Added ``tempdata()``, ``set_tempdata()``, and ``unset_tempdata()`` methods for manipulating tempdata. + - ``keep_flashdata()`` now accepts an array of keys. + - :doc:`File Uploading Library <libraries/file_uploading>` changes include: + - Added **max_filename_increment** config setting. + - Added an **index** parameter to the ``data()`` method. + - Added the **min_width** and **min_height** options for images. - :doc:`Cart library <libraries/cart>` changes include: - - It now auto-increments quantity's instead of just resetting it, this is the default behaviour of large e-commerce sites. - - Product Name strictness can be disabled via the Cart Library by switching "$product_name_safe". - - Added function remove() to remove a cart item, updating with quantity of 0 seemed like a hack but has remained to retain compatibility. + - ``insert()`` now auto-increments quantity for an item when inserted twice instead of resetting it, this is the default behaviour of large e-commerce sites. + - *Product Name* strictness can be disabled by switching the ``$product_name_safe`` property to FALSE. + - 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. - - 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. - - Property maintain_ratio is now taken into account when resizing images using ImageMagick library - - Removed SHA1 function in the :doc:`Encryption Library <libraries/encryption>`. - - Added $config['csrf_regeneration'] to the CSRF protection in the :doc:`Security library <libraries/security>`, which makes token regeneration optional. - - Added $config['csrf_exclude_uris'] to the CSRF protection in the :doc:`Security library <libraries/security>`, which allows you list URIs which will not have the CSRF validation functions run. + - 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. + - Property *maintain_ratio* is now taken into account when resizing images using ImageMagick library. + - Added support for maintaining transparency for PNG images in method ``text_watermark()``. - :doc:`Form Validation library <libraries/form_validation>` changes include: - - Added method error_array() to return all error messages as an array. - - Added method set_data() to set an alternative data array to be validated instead of the default $_POST. - - Added method reset_validation(), which resets internal validation variables in case of multiple validation routines. - - Added support for setting error delimiters in the config file via $config['error_prefix'] and $config['error_suffix']. - - _execute() now considers input data to be invalid if a specified rule is not found. - - Removed method is_numeric() as it exists as a native PHP function and _execute() will find and use that (the 'is_numeric' rule itself is deprecated since 1.6.1). + - Added method ``error_array()`` to return all error messages as an array. + - Added method ``set_data()`` to set an alternative data array to be validated instead of the default ``$_POST``. + - Added method ``reset_validation()`` which resets internal validation variables in case of multiple validation routines. + - Added support for setting error delimiters in the config file via ``$config['error_prefix']`` and ``$config['error_suffix']``. + - Internal method ``_execute()`` now considers input data to be invalid if a specified rule is not found. + - Removed method ``is_numeric()`` as it exists as a native PHP function and ``_execute()`` will find and use that (the **is_numeric** rule itself is deprecated since 1.6.1). - Native PHP functions used as rules can now accept an additional parameter, other than the data itself. - - Updated set_rules() to accept an array of rules as well as a string. - - Changed the :doc:`Session Library <libraries/sessions>` to select only one row when using database sessions. - - Added all_flashdata() method to session class. Returns an associative array of only flashdata. - - Allowed for setting table class defaults in a config file. - - Added a Wincache driver to the :doc:`Caching Library <libraries/caching>`. - - Added a Redis driver to the :doc:`Caching Library <libraries/caching>`. - - Added dsn (delivery status notification) option to the :doc:`Email Library <libraries/email>`. - - Renamed method _set_header() to set_header() and made it public to enable adding custom headers in the :doc:`Email Library <libraries/email>`. - - Added an "index" parameter to the data() method in the :doc:`Upload Library <libraries/file_uploading>`. + - Updated method ``set_rules()`` to accept an array of rules as well as a string. + - Fields that have empty rules set no longer run through validation (and therefore are not considered erroneous). + - Added rule **differs* to check if the value of a field differs from the value of another field. + - Added rule **valid_url**. + - Added support for named parameters in error messages. + - :doc:`Language <libraries/language>` line keys must now be prefixed with **form_validation_**. + - Added support for setting :doc:`Table <libraries/table>` class defaults in a config file. + - :doc:`Caching Library <libraries/caching>` changes include: + - Added Wincache driver. + - Added Redis driver. + - Added a *key_prefix* option for cache IDs. + - :doc:`Email library <libraries/email>` changes include: + - Added custom filename to ``Email::attach()`` as ``$this->email->attach($filename, $disposition, $newname)``. + - Added possibility to send attachment as buffer string in ``Email::attach()`` as ``$this->email->attach($buffer, $disposition, $newname, $mime)``. + - Added dsn (delivery status notification) option. + - Renamed method _set_header() to set_header() and made it public to enable adding custom headers in the :doc:`Email Library <libraries/email>`. + - Successfully sent emails will automatically clear the parameters. + - Added a *return_path* parameter to the ``from()`` method. + - Removed the second parameter (character limit) from internal method ``_prep_quoted_printable()`` as it is never used. + - Internal method ``_prep_quoted_printable()`` will now utilize the native ``quoted_printable_encode()``, ``imap_8bit()`` functions (if available) when CRLF is set to "\r\n". + - Default charset now relies on the global ``$config['charset']`` setting. + - Removed unused protected method ``_get_ip()`` (:doc:`Input Library <libraries/input>`'s ``ip_address()`` should be used anyway). + - Internal method ``_prep_q_encoding()`` now utilizes PHP's *mbstring* and *iconv* extensions (when available) and no longer has a second (``$from``) argument. + - Added an optional parameter to ``print_debugger()`` to allow specifying which parts of the message should be printed ('headers', 'subject', 'body'). - :doc:`Pagination Library <libraries/pagination>` changes include: - Added support for the anchor "rel" attribute. - Added support for setting custom attributes. - Deprecated usage of the "anchor_class" setting (use the new "attributes" setting instead). - Added $config['reuse_query_string'] to allow automatic repopulation of query string arguments, combined with normal URI segments. + - Removed the default `` `` from a number of the configuration variables. - Added the ability to use a proxy with the :doc:`XML-RPC Library <libraries/xmlrpc>`. + - :doc:`Encryption Library <libraries/encryption>` changes include: + - Added support for hashing algorithms other than SHA1 and MD5. + - Removed previously deprecated ``sha1()`` method. + - :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_type']`` to allow switching between *sequential* and *timestamp* migrations. + - :doc:`User Agent Library <libraries/user_agent>` will now check if robots are pretending to be mobile clients (helps with e.g. Google indexing mobile website versions). - Core - - Changed private methods in the :doc:`URI Library <libraries/uri>` to protected so MY_URI can override them. - - Removed CI_CORE boolean constant from CodeIgniter.php (no longer Reactor and Core versions). - - Added method get_vars() to the :doc:`Loader Library <libraries/loader>` to retrieve all variables loaded with $this->load->vars(). - - is_loaded() function from system/core/Commons.php now returns a reference. - - $config['rewrite_short_tags'] now has no effect when using PHP 5.4 as *<?=* will always be available. - - Added method() to the :doc:`Input Library <libraries/input>` to retrieve $_SERVER['REQUEST_METHOD']. - - Modified valid_ip() to use PHP's filter_var() in the :doc:`Input Library <libraries/input>`. - - 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>`. - - Added get_content_type() method to the :doc:`Output Library <libraries/output>`. - - Added get_mimes() function to system/core/Commons.php to return the config/mimes.php array. - - Added a second argument to set_content_type() in the :doc:`Output Library <libraries/output>` that allows setting the document charset as well. - - $config['time_reference'] now supports all timezone strings supported by PHP. - - Added support for HTTP code 303 ("See Other") in set_status_header(). - - Changed :doc:`Config Library <libraries/config>` method site_url() to accept an array as well. - - Added method ``strip_image_tags()`` to the :doc:`Security Library <libraries/security>`. + - :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()``. + - ``_ci_autoloader()`` is now a protected method. + - Added autoloading of drivers with ``$autoload['drivers']``. + - ``$config['rewrite_short_tags']`` now has no effect when using PHP 5.4 as ``<?=`` will always be available. + - Changed method ``config()`` to return whatever ``CI_Config::load()`` returns instead of always being void. + - :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 :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 :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: + - Added a second argument to method ``set_content_type()`` that allows setting the document charset as well. + - Added methods ``get_content_type()`` and ``get_header()``. + - Added method ``delete_cache()``. + - ``$config['time_reference']`` now supports all timezone strings supported by PHP. + - :doc:`Config Library <libraries/config>` changes include: + - Changed ``site_url()`` method to accept an array as well. + - Removed internal method ``_assign_to_config()`` and moved it's implementation in *CodeIgniter.php* instead. + - :doc:`Security Library <libraries/security>` changes include: + - 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). + - :doc:`Language Library <libraries/language>` changes include: + - Changed method ``load()`` to filter the language name with ``ctype_digit()``. + - Added an optional second parameter to method ``line()`` to disable error login for line keys that were not found. + - Language files are now loaded in a cascading style with the one in **system/** always loaded and overriden afterwards, if another one is found. Bug fixes for 3.0 ------------------ @@ -208,9 +327,9 @@ Bug fixes for 3.0 - Fixed a bug (#181) where a mis-spelling was in the form validation language file. - Fixed a bug (#159, #163) that mishandled Query Builder nested transactions because _trans_depth was not getting incremented. - Fixed a bug (#737, #75) - :doc:`Pagination <libraries/pagination>` anchor class was not set properly when using initialize method. -- Fixed a bug (#419) - auto_link() now recognizes URLs that come after a word boundary. -- Fixed a bug (#724) - is_unique in form validation now checks that you are connected to a database. -- Fixed a bug (#647) - _get_mod_time() in Zip library no longer generates stat failed errors. +- Fixed a bug (#419) - ``auto_link()`` now recognizes URLs that come after a word boundary. +- Fixed a bug (#724) - :doc:`Form Validation Library <libraries/form_validation>` rule **is_unique** didn't check if a database connection exists. +- Fixed a bug (#647) - :doc:`Zip Library <libraries/zip>` internal method ``_get_mod_time()`` didn't suppress possible "stat failed" errors generated by ``filemtime()``. - Fixed a bug (#608) - Fixes an issue with the Image_lib class not clearing properties completely. - Fixed a bug (#157, #174) - the Image_lib clear() function now resets all variables to their default values. - Fixed a bug where using $this->dbforge->create_table() with PostgreSQL database could lead to fetching whole table. @@ -234,23 +353,20 @@ Bug fixes for 3.0 - Fixed a bug (#129) - ODBC's num_rows() returned -1 in some cases, due to not all subdrivers supporting the odbc_num_rows() function. - Fixed a bug (#153) - E_NOTICE being generated by getimagesize() in the :doc:`File Uploading Library <libraries/file_uploading>`. - Fixed a bug (#611) - SQLSRV's error handling methods used to issue warnings when there's no actual error. -- Fixed a bug (#1036) - is_write_type() method in the :doc:`Database Library <database/index>` didn't return TRUE for RENAME queries. +- Fixed a bug (#1036) - ``is_write_type()`` method in the :doc:`Database Library <database/index>` didn't return TRUE for RENAME queries. - Fixed a bug in PDO's _version() method where it used to return the client version as opposed to the server one. - Fixed a bug in PDO's insert_id() method where it could've failed if it's used with Postgre versions prior to 8.1. - Fixed a bug in CUBRID's affected_rows() method where a connection resource was passed to cubrid_affected_rows() instead of a result. - Fixed a bug (#638) - db_set_charset() ignored its arguments and always used the configured charset instead. - Fixed a bug (#413) - Oracle's error handling methods used to only return connection-related errors. -- Fixed a bug (#804) - Profiler library was trying to handle objects as strings in some cases, resulting in warnings being issued by htmlspecialchars(). - Fixed a bug (#1101) - MySQL/MySQLi result method field_data() was implemented as if it was handling a DESCRIBE result instead of the actual result set. - Fixed a bug in Oracle's :doc:`Database Forge Class <database/forge>` method _create_table() where it failed with AUTO_INCREMENT as it's not supported. - Fixed a bug (#1080) - When using the SMTP protocol, the :doc:`Email Library <libraries/email>` send() method was returning TRUE even if the connection/authentication against the server failed. -- Fixed a bug (#499) - a CSRF cookie was created even with CSRF protection being disabled. - Fixed a bug (#306) - ODBC's insert_id() method was calling non-existent function odbc_insert_id(), which resulted in a fatal error. - Fixed a bug in Oracle's DB_result class where the cursor id passed to it was always NULL. - Fixed a bug (#64) - Regular expression in DB_query_builder.php failed to handle queries containing SQL bracket delimiters in the join condition. - Fixed a bug in the :doc:`Session Library <libraries/sessions>` where a PHP E_NOTICE error was triggered by _unserialize() due to results from databases such as MSSQL and Oracle being space-padded on the right. - Fixed a bug (#501) - set_rules() to check if the request method is not 'POST' before aborting, instead of depending on count($_POST) in the :doc:`Form Validation Library <libraries/form_validation>`. -- Fixed a bug (#940) - csrf_verify() used to set the CSRF cookie while processing a POST request with no actual POST data, which resulted in validating a request that should be considered invalid. - Fixed a bug (#136) - PostgreSQL, MySQL and MySQLi's escape_str() method didn't properly escape LIKE wild characters. - Fixed a bug in the library loader where some PHP versions wouldn't execute the class constructor. - Fixed a bug (#88) - An unexisting property was used for configuration of the Memcache cache driver. @@ -269,7 +385,6 @@ Bug fixes for 3.0 - Fixed a bug (#1265) - Database connections were always closed, regardless of the 'pconnect' option value. - Fixed a bug (#128) - :doc:`Language Library <libraries/language>` did not correctly keep track of loaded language files. - Fixed a bug (#1242) - Added Windows path compatibility to function read_dir of ZIP library. -- Fixed a bug (#1314) - sess_destroy() did not destroy userdata. - Fixed a bug (#1349) - get_extension() in the :doc:`File Uploading Library <libraries/file_uploading>` returned the original filename when it didn't have an actual extension. - Fixed a bug (#1273) - E_NOTICE being generated by :doc:`Query Builder <database/query_builder>`'s set_update_batch() method. - Fixed a bug (#44, #110) - :doc:`Upload library <libraries/file_uploading>`'s clean_file_name() method didn't clear '!' and '#' characters. @@ -283,14 +398,13 @@ Bug fixes for 3.0 - Fixed a bug (#666) - :doc:`Output library <libraries/output>`'s set_content_type() method didn't set the document charset. - Fixed a bug (#784, #861) - :doc:`Database Forge <database/forge>` method ``create_table()`` used to accept constraints for MSSQL/SQLSRV integer-type columns. - Fixed a bug (#706) - SQLSRV/MSSSQL didn't escape field names. -- Fixed a bug (#1452) - protect_identifiers() didn't properly detect identifiers with spaces in their names. -- Fixed a bug where protect_identifiers() ignored it's extra arguments when the value passed to it is an array. -- Fixed a bug where _has_operator() didn't detect BETWEEN. -- Fixed a bug in :doc:`Query Builder <database/query_builder>`'s join() method where it failed with identifiers containing dashes. +- Fixed a bug (#1452) - ``protect_identifiers()`` didn't properly detect identifiers with spaces in their names. +- Fixed a bug where ``protect_identifiers()`` ignored it's extra arguments when the value passed to it is an array. +- Fixed a bug where ``_has_operator()`` didn't detect BETWEEN. +- Fixed a bug in :doc:`Query Builder <database/query_builder>`'s ``join()`` method where it failed with identifiers containing dashes. - Fixed a bug (#1264) - :doc:`Database Forge <database/forge>` and :doc:`Database Utilities <database/utilities>` didn't update/reset the databases and tables list cache when a table or a database is created, dropped or renamed. -- Fixed a bug (#7) - :doc:`Query Builder <database/query_builder>`'s join() method only escaped one set of conditions. +- Fixed a bug (#7) - :doc:`Query Builder <database/query_builder>`'s ``join()`` method only escaped one set of conditions. - Fixed a bug (#1321) - Core Exceptions class couldn't find the errors/ folder in some cases. -- Fixed a bug in the File-based :doc:`Cache Library <libraries/caching>` driver's get_metadata() method where a non-existent array key was accessed for the TTL value. - Fixed a bug (#1202) - :doc:`Encryption Library <libraries/encryption>` encode_from_legacy() didn't set back the encrypt mode on failure. - Fixed a bug (#145) - compile_binds() failed when the bind marker was present in a literal string within the query. - Fixed a bug in protect_identifiers() where if passed along with the field names, operators got escaped as well. @@ -299,15 +413,83 @@ Bug fixes for 3.0 - Fixed a bug (#520) - :doc:`Date Helper <helpers/date_helper>` function nice_date() failed when the optional second parameter is not passed. - Fixed a bug (#167) - ``$config['permitted_uri_chars']`` didn't affect URL-encoded characters. - Fixed a bug (#318) - :doc:`Profiling <general/profiling>` setting *query_toggle_count* was not settable as described in the manual. -- Fixed a bug (#938) - :doc:`Config Library <libraries/config>` method site_url() added a question mark to the URL string when query strings are enabled even if it already existed. -- Fixed a bug (#999) - :doc:`Config Library <libraries/config>` method site_url() always appended ``$config['url_suffix']`` to the end of the URL string, regardless of wether a query string exists in it. -- Fixed a bug where :doc:`URL Helper <helpers/url_helper>` function anchor_popup() ignored the attributes argument if it is not an array. +- Fixed a bug (#938) - :doc:`Config Library <libraries/config>` method ``site_url()`` added a question mark to the URL string when query strings are enabled even if it already existed. +- Fixed a bug (#999) - :doc:`Config Library <libraries/config>` method ``site_url()`` always appended ``$config['url_suffix']`` to the end of the URL string, regardless of whether a query string exists in it. +- Fixed a bug where :doc:`URL Helper <helpers/url_helper>` function ``anchor_popup()`` ignored the attributes argument if it is not an array. - Fixed a bug (#1328) - :doc:`Form Validation Library <libraries/form_validation>` didn't properly check the type of the form fields before processing them. - Fixed a bug (#79) - :doc:`Form Validation Library <libraries/form_validation>` didn't properly validate array fields that use associative keys or have custom indexes. - Fixed a bug (#427) - :doc:`Form Validation Library <libraries/form_validation>` method ``strip_image_tags()`` was an alias to a non-existent method. - Fixed a bug (#1545) - :doc:`Query Builder <database/query_builder>` method ``limit()`` wasn't executed properly under Oracle. - Fixed a bug (#1551) - :doc:`Date Helper <helpers/date_helper>` function ``standard_date()`` didn't properly format *W3C* and *ATOM* standard dates. - Fixed a bug in :doc:`Query Builder <database/query_builder>` method join() where literal values were escaped as if they were fields. +- Fixed a bug (#135) - PHP Error logging was impossible without the errors being displayed. +- Fixed a bug (#1613) - :doc:`Form Helper <helpers/form_helper>` functions ``form_multiselect()``, ``form_dropdown()`` didn't properly handle empty array option groups. +- Fixed a bug (#1605) - :doc:`Pagination Library <libraries/pagination>` produced incorrect *previous* and *next* link values. +- Fixed a bug in SQLSRV's ``affected_rows()`` method where an erroneous function name was used. +- Fixed a bug (#1000) - Change syntax of ``$view_file`` to ``$_ci_view_file`` to prevent being overwritten by application. +- Fixed a bug (#1757) - :doc:`Directory Helper <helpers/directory_helper>` function ``directory_map()`` was skipping files and directories named *0*. +- Fixed a bug (#1789) - :doc:`Database Library <database/index>` method ``escape_str()`` escaped quote characters in LIKE conditions twice under MySQL. +- Fixed a bug (#395) - :doc:`Unit Testing Library <libraries/unit_testing>` method ``result()`` didn't properly check array result columns when called from ``report()``. +- Fixed a bug (#1692) - :doc:`Database Library <database/index>` method ``display_error()`` didn't properly trace the possible error source on Windows systems. +- Fixed a bug (#1745) - ``is_write_type()`` method in the :doc:`Database Library <database/index>` didn't return TRUE for LOAD queries. +- Fixed a bug (#1765) - :doc:`Database Library <database/index>` didn't properly detect connection errors for MySQLi. +- Fixed a bug (#1257) - :doc:`Query Builder <database/query_builder>` used to (unnecessarily) group FROM clause contents, which breaks certain queries and is invalid for some databases. +- Fixed a bug (#1709) - :doc:`Email <libraries/email>` headers were broken when using long email subjects and \r\n as CRLF. +- Fixed a bug where ``MB_ENABLED`` was only declared if ``UTF8_ENABLED`` was set to TRUE. +- Fixed a bug where the :doc:`Session Library <libraries/sessions>` accepted cookies with *last_activity* values being in the future. +- Fixed a bug (#1897) - :doc:`Email Library <libraries/email>` triggered PHP E_WARNING errors when *mail* protocol used and ``to()`` is never called. +- Fixed a bug (#1409) - :doc:`Email Library <libraries/email>` didn't properly handle multibyte characters when applying Q-encoding to headers. +- Fixed a bug where :doc:`Email Library <libraries/email>` didn't honor it's *wordwrap* setting while handling alternative messages. +- Fixed a bug (#1476, #1909) - :doc:`Pagination Library <libraries/pagination>` didn't take into account actual routing when determining the current page. +- Fixed a bug (#1766) - :doc:`Query Builder <database/query_builder>` didn't always take into account the *dbprefix* setting. +- Fixed a bug (#779) - :doc:`URI Class <libraries/uri>` didn't always trim slashes from the *uri_string* as shown in the documentation. +- Fixed a bug (#134) - :doc:`Database Caching <database/caching>` method ``delete_cache()`` didn't work in some cases due to *cachedir* not being initialized properly. +- Fixed a bug (#191) - :doc:`Loader Library <libraries/loader>` ignored attempts for (re)loading databases to ``get_instance()->db`` even when the old database connection is dead. +- Fixed a bug (#1255) - :doc:`User Agent Library <libraries/user_agent>` method ``is_referral()`` only checked if ``$_SERVER['HTTP_REFERER']`` exists. +- Fixed a bug (#1146) - :doc:`Download Helper <helpers/download_helper>` function ``force_download()`` incorrectly sent *Cache-Control* directives *pre-check* and *post-check* to Internet Explorer. +- Fixed a bug (#1811) - :doc:`URI Library <libraries/uri>` didn't properly cache segments for ``uri_to_assoc()`` and ``ruri_to_assoc()``. +- Fixed a bug (#1506) - :doc:`Form Helpers <helpers/form_helper>` set empty *name* attributes. +- Fixed a bug (#59) - :doc:`Query Builder <database/query_builder>` method ``count_all_results()`` ignored the DISTINCT clause. +- Fixed a bug (#1624) - :doc:`Form Validation Library <libraries/form_validation>` rule **matches** didn't property handle array field names. +- Fixed a bug (#1630) - :doc:`Form Helper <helpers/form_helper>` function ``set_value()`` didn't escape HTML entities. +- 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 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. +- Fixed a bug (#18) - :doc:`APC Cache <libraries/caching>` driver didn't (un)serialize data, resulting in failure to store objects. +- Fixed a bug (#188) - :doc:`Unit Testing Library <libraries/unit_testing>` filled up logs with error messages for non-existing language keys. +- Fixed a bug (#113) - :doc:`Form Validation Library <libraries/form_validation>` didn't properly handle empty fields that were specified as an array. +- Fixed a bug (#2061) - :doc:`Routing Class <general/routing>` didn't properly sanitize directory, controller and function triggers with **enable_query_strings** set to TRUE. + +Version 2.1.3 +============= + +Release Date: October 8, 2012 + +- Core + - :doc:`Common function <general/common_functions>` ``is_loaded()`` now returns a reference. + +Bug fixes for 2.1.3 +------------------- + +- Fixed a bug (#1543) - File-based :doc:`Caching <libraries/caching>` method ``get_metadata()`` used a non-existent array key to look for the TTL value. +- Fixed a bug (#1314) - :doc:`Session Library <libraries/sessions>` method ``sess_destroy()`` didn't destroy the userdata array. +- Fixed a bug (#804) - :doc:`Profiler library <general/profiling>` was trying to handle objects as strings in some cases, resulting in *E_WARNING* messages being issued by ``htmlspecialchars()``. +- Fixed a bug (#1699) - :doc:`Migration Library <libraries/migration>` ignored the ``$config['migration_path']`` setting. +- Fixed a bug (#227) - :doc:`Input Library <libraries/input>` allowed unconditional spoofing of HTTP clients' IP addresses through the *HTTP_CLIENT_IP* header. +- Fixed a bug (#907) - :doc:`Input Library <libraries/input>` ignored *HTTP_X_CLUSTER_CLIENT_IP* and *HTTP_X_CLIENT_IP* headers when checking for proxies. +- Fixed a bug (#940) - ``csrf_verify()`` used to set the CSRF cookie while processing a POST request with no actual POST data, which resulted in validating a request that should be considered invalid. +- Fixed a bug (#499) - :doc:`Security Library <libraries/security>` where a CSRF cookie was created even if ``$config['csrf_protection']`` is set tot FALSE. +- Fixed a bug (#1715) - :doc:`Input Library <libraries/input>` triggered ``csrf_verify()`` on CLI requests. +- Fixed a bug (#751) - :doc:`Query Builder <database/query_builder>` didn't properly handle cached field escaping overrides. +- Fixed a bug (#2004) - :doc:`Query Builder <database/query_builder>` didn't properly merge cached calls with non-cache ones. Version 2.1.2 ============= @@ -2237,7 +2419,7 @@ Release Date: September 17, 2006 - Moved the list of "allowed URI characters" out of the Router class and into the config file. - Moved the MIME type array out of the Upload class and into its own - file in the applications/config/ folder. + file in the application/config/ folder. - Updated the Upload class to allow the upload field name to be set when calling :doc:`do_upload() <./libraries/file_uploading>`. - Updated the :doc:`Config Library <./libraries/config>` to be able to diff --git a/user_guide_src/source/conf.py b/user_guide_src/source/conf.py index e972a388b..f68405b36 100644 --- a/user_guide_src/source/conf.py +++ b/user_guide_src/source/conf.py @@ -167,6 +167,7 @@ html_last_updated_fmt = '%b %d, %Y' # Output file base name for HTML help builder. htmlhelp_basename = 'CodeIgniterdoc' +html_copy_source = False # -- Options for LaTeX output -------------------------------------------------- diff --git a/user_guide_src/source/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/configuration.rst b/user_guide_src/source/database/configuration.rst index c17de600a..34cefffbd 100644 --- a/user_guide_src/source/database/configuration.rst +++ b/user_guide_src/source/database/configuration.rst @@ -28,6 +28,8 @@ prototype:: 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'autoinit' => TRUE, + 'encrypt' => FALSE, + 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array() ); @@ -69,6 +71,8 @@ These failovers can be specified by setting the failover for a connection like t 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'autoinit' => TRUE, + 'encrypt' => FALSE, + 'compress' => FALSE, 'stricton' => FALSE ), array( @@ -86,6 +90,8 @@ These failovers can be specified by setting the failover for a connection like t 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'autoinit' => TRUE, + 'encrypt' => FALSE, + 'compress' => FALSE, 'stricton' => FALSE ) ); @@ -115,6 +121,8 @@ example, to set up a "test" environment you would do this:: 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'autoinit' => TRUE, + 'compress' => FALSE, + 'encrypt' => FALSE, 'stricton' => FALSE, 'failover' => array() ); @@ -174,11 +182,14 @@ Explanation of Values: customizable by the end user. **autoinit** Whether or not to automatically connect to the database when the library loads. If set to false, the connection will take place prior to executing the first query. +**schema** The database schema, defaults to 'public'. Used by PostgreSQL and ODBC drivers. +**encrypt** Whether or not to use an encrypted connection. +**compress** Whether or not to use client compression (MySQL only). **stricton** TRUE/FALSE (boolean) - Whether to force "Strict Mode" connections, good for ensuring strict SQL while developing an application. **port** The database port number. To use this value you have to add a line to the database config array. :: - + $db['default']['port'] = 5432; ====================== ================================================================================================== diff --git a/user_guide_src/source/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/query_builder.rst b/user_guide_src/source/database/query_builder.rst index b86a0c8db..65609c1cb 100644 --- a/user_guide_src/source/database/query_builder.rst +++ b/user_guide_src/source/database/query_builder.rst @@ -345,23 +345,24 @@ if appropriate $this->db->like() ================= -This function enables you to generate **LIKE** clauses, useful for doing +This method enables you to generate **LIKE** clauses, useful for doing searches. -.. note:: All values passed to this function are escaped automatically. +.. note:: All values passed to this method are escaped automatically. #. **Simple key/value method:** :: - $this->db->like('title', 'match'); // Produces: WHERE title LIKE '%match%' + $this->db->like('title', 'match'); + // Produces: WHERE `title` LIKE '%match%' ESCAPE '!' - If you use multiple function calls they will be chained together with + If you use multiple method calls they will be chained together with AND between them:: $this->db->like('title', 'match'); $this->db->like('body', 'match'); - // WHERE title LIKE '%match%' AND body LIKE '%match% + // WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!' If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and @@ -369,9 +370,9 @@ searches. :: - $this->db->like('title', 'match', 'before'); // Produces: WHERE title LIKE '%match' - $this->db->like('title', 'match', 'after'); // Produces: WHERE title LIKE 'match%' - $this->db->like('title', 'match', 'both'); // Produces: WHERE title LIKE '%match%' + $this->db->like('title', 'match', 'before'); // Produces: WHERE `title` LIKE '%match' ESCAPE '!' + $this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!' + $this->db->like('title', 'match', 'both'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!' #. **Associative array method:** @@ -379,37 +380,37 @@ searches. $array = array('title' => $match, 'page1' => $match, 'page2' => $match); $this->db->like($array); - // WHERE title LIKE '%match%' AND page1 LIKE '%match%' AND page2 LIKE '%match%' + // WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!' $this->db->or_like() ==================== -This function is identical to the one above, except that multiple +This method is identical to the one above, except that multiple instances are joined by OR:: $this->db->like('title', 'match'); $this->db->or_like('body', $match); - // WHERE title LIKE '%match%' OR body LIKE '%match%' + // WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!' -.. note:: or_like() was formerly known as orlike(), which has been removed. +.. note:: ``or_like()`` was formerly known as ``orlike()``, which has been removed. $this->db->not_like() ===================== -This function is identical to **like()**, except that it generates NOT -LIKE statements:: +This method is identical to ``like()``, except that it generates +NOT LIKE statements:: - $this->db->not_like('title', 'match'); // WHERE title NOT LIKE '%match% + $this->db->not_like('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!' $this->db->or_not_like() ======================== -This function is identical to **not_like()**, except that multiple +This method is identical to ``not_like()``, except that multiple instances are joined by OR:: $this->db->like('title', 'match'); $this->db->or_not_like('body', 'match'); - // WHERE title LIKE '%match% OR body NOT LIKE '%match%' + // WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!' $this->db->group_by() ===================== @@ -469,31 +470,47 @@ Identical to having(), only separates multiple clauses with "OR". $this->db->order_by() ===================== -Lets you set an ORDER BY clause. The first parameter contains the name -of the column you would like to order by. The second parameter lets you -set the direction of the result. Options are asc or desc, or random. +Lets you set an ORDER BY clause. + +The first parameter contains the name of the column you would like to order by. + +The second parameter lets you set the direction of the result. +Options are **ASC**, **DESC** AND **RANDOM**. :: - $this->db->order_by("title", "desc"); // Produces: ORDER BY title DESC + $this->db->order_by('title', 'DESC'); + // Produces: ORDER BY `title` DESC You can also pass your own string in the first parameter:: - $this->db->order_by('title desc, name asc'); // Produces: ORDER BY title DESC, name ASC + $this->db->order_by('title DESC, name ASC'); + // Produces: ORDER BY `title` DESC, `name` ASC Or multiple function calls can be made if you need multiple fields. :: - $this->db->order_by("title", "desc"); - $this->db->order_by("name", "asc"); // Produces: ORDER BY title DESC, name ASC + $this->db->order_by('title', 'DESC'); + $this->db->order_by('name', 'ASC'); + // Produces: ORDER BY `title` DESC, `name` ASC + +If you choose the **RANDOM** direction option, then the first parameters will +be ignored, unless you specify a numeric seed value. + +:: + + $this->db->order_by('title', 'RANDOM'); + // Produces: ORDER BY RAND() + $this->db->order_by(42, 'RANDOM'); + // Produces: ORDER BY RAND(42) .. note:: order_by() was formerly known as orderby(), which has been removed. -.. note:: random ordering is not currently supported in Oracle or MSSQL - drivers. These will default to 'ASC'. +.. note:: Random ordering is not currently supported in Oracle and + will default to ASC instead. $this->db->limit() ================== @@ -681,6 +698,35 @@ associative array of values. .. note:: All values are escaped automatically producing safer queries. +$this->db->replace() +==================== + +This method executes a REPLACE statement, which is basically the SQL +standard for (optional) DELETE + INSERT, using *PRIMARY* and *UNIQUE* +keys as the determining factor. +In our case, it will save you from the need to implement complex +logics with different combinations of ``select()``, ``update()``, +``delete()`` and ``insert()`` calls. + +Example:: + + $data = array( + 'title' => 'My title', + 'name' => 'My Name', + 'date' => 'My date' + ); + + $this->db->replace('table', $data); + + // Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date') + +In the above example, if we assume that the *title* field is our primary +key, then if a row containing 'My title' as the *title* value, that row +will be deleted with our new row data replacing it. + +Usage of the ``set()`` method is also allowed and all fields are +automatically escaped, just like with ``insert()``. + $this->db->set() ================ @@ -740,7 +786,6 @@ Or an object:: $this->db->set($object); $this->db->insert('mytable'); - ************* Updating Data ************* @@ -792,6 +837,7 @@ Or as an array:: You may also use the $this->db->set() function described above when performing updates. + $this->db->update_batch() ========================= @@ -830,6 +876,10 @@ array of values, the third parameter is the where key. .. note:: All values are escaped automatically producing safer queries. +.. note:: ``affected_rows()`` won't give you proper results with this method, + due to the very nature of how it works. Instead, ``update_batch()`` + returns the number of rows affected. + $this->db->get_compiled_update() ================================ @@ -1005,4 +1055,4 @@ run the query:: $data = $this->db->get()->result_array(); // Would execute and return an array of results of the following query: - // SELECT field1, field1 from mytable where field3 = 5; + // SELECT field1, field1 from mytable where field3 = 5;
\ No newline at end of file diff --git a/user_guide_src/source/database/results.rst b/user_guide_src/source/database/results.rst index d032f734e..e0a87a851 100644 --- a/user_guide_src/source/database/results.rst +++ b/user_guide_src/source/database/results.rst @@ -99,7 +99,7 @@ to instantiate the row with:: echo $row->reverse_name(); // or methods defined on the 'User' class row_array() -============ +=========== Identical to the above row() function, except it returns an array. Example:: @@ -138,12 +138,12 @@ parameter: .. note:: all the functions above will load the whole result into memory (prefetching) use unbuffered_row() for processing large result sets. -unbuffered_row($type) -===================== +unbuffered_row() +================ -This function returns a single result row without prefetching the whole result in memory as row() does. -If your query has more than one row, it returns the current row and moves the internal data pointer ahead. -The result is returned as $type could be 'object' (default) or 'array' that will return an associative array. +This method returns a single result row without prefetching the whole +result in memory as ``row()`` does. If your query has more than one row, +it returns the current row and moves the internal data pointer ahead. :: @@ -156,12 +156,19 @@ The result is returned as $type could be 'object' (default) or 'array' that will echo $row->body; } +You can optionally pass 'object' (default) or 'array' in order to specify +the returned value's type:: + + $query->unbuffered_row(); // object + $query->unbuffered_row('object'); // object + $query->unbuffered_row('array'); // associative array + *********************** Result Helper Functions *********************** $query->num_rows() -=================== +================== The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:: @@ -177,7 +184,7 @@ is the variable that the query result object is assigned to:: resulting array in order to achieve the same functionality. $query->num_fields() -===================== +==================== The number of FIELDS (columns) returned by the query. Make sure to call the function using your query result object:: @@ -187,7 +194,7 @@ the function using your query result object:: echo $query->num_fields(); $query->free_result() -====================== +===================== It frees the memory associated with the result and deletes the result resource ID. Normally PHP frees its memory automatically at the end of @@ -209,3 +216,21 @@ Example:: $row = $query2->row(); echo $row->name; $query2->free_result(); // The $query2 result object will no longer be available + +data_seek() +=========== + +This method sets the internal pointer for the next result row to be +fetched. It is only useful in combination with ``unbuffered_row()``. + +It accepts a positive integer value, which defaults to 0 and returns +TRUE on success or FALSE on failure. + +:: + + $query = $this->db->query('SELECT `field_name` FROM `table_name`'); + $query->data_seek(5); // Skip the first 5 rows + $row = $query->unbuffered_row(); + +.. note:: Not all database drivers support this feature and will return FALSE. + Most notably - you won't be able to use it with PDO.
\ No newline at end of file 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 259a4987e..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: -- Core 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..48385d6c9 100644 --- a/user_guide_src/source/general/caching.rst +++ b/user_guide_src/source/general/caching.rst @@ -23,36 +23,46 @@ 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 manually delete the cache, you can use the ``delete_cache()`` +method:: + + // Deletes cache for the currently requested URI + $this->output->delete_cache(); + + // Deletes cache for /foo/bar + $this->output->delete_cache('/foo/bar');
\ 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 7dc1ca319..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,15 +44,14 @@ 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:: example.com/index.php/tools/message/to -Instead, we are going to open Terminal in Mac/Lunix or go to Run > "cmd" +Instead, we are going to open Terminal in Mac/Linux or go to Run > "cmd" in Windows and navigate to our CodeIgniter project. .. code-block:: bash @@ -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 99126f900..7917d3239 100644 --- a/user_guide_src/source/general/common_functions.rst +++ b/user_guide_src/source/general/common_functions.rst @@ -6,58 +6,118 @@ 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) + + :param string $file: File path + :returns: bool -is_writable() returns TRUE on Windows servers when you really can't +``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() +============ + +.. 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 calls ``CI_Exception::show_error()``. For more info, +please see the :doc:`Error Handling <errors>` documentation. + +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 -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. +This function is an alias for ``CI_Log::write_log()``. For more info, +please see the :doc:`Error Handling <errors>` documentation. -show_error('message'), show_404('page'), log_message('level', 'message') -======================================================================== +set_status_header() +=============================== -These are each outlined on the :doc:`Error Handling <errors>` page. +.. php:function:: set_status_header($code, $text = '') -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:: @@ -67,20 +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() +============================= -This function prevents inserting null characters between ascii +.. 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 characters, like Java\\0script. -html_escape($mixed) -==================== +Example:: -This function provides short cut for htmlspecialchars() function. It -accepts string and array. To prevent Cross Site Scripting (XSS), it is -very useful. + remove_invisible_characters('Java\\0script'); + // Returns: 'Javascript' -get_mimes() +html_escape() ============= -This function returns the MIMEs array from config/mimes.php.
\ No newline at end of file +.. 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() +=========== + +.. 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). + +function_usable() +================= + +.. 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/quick_reference.rst b/user_guide_src/source/general/quick_reference.rst deleted file mode 100644 index b9108a528..000000000 --- a/user_guide_src/source/general/quick_reference.rst +++ /dev/null @@ -1,11 +0,0 @@ -##################### -Quick Reference Chart -##################### - -For a PDF version of this chart, `click -here <http://codeigniter.com/download_files/ci_quick_ref.pdf>`_. - -.. figure:: ../images/ci_quick_ref.png - :align: center - :alt: - 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 5ce7fc2ff..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,32 +25,35 @@ 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 --------- - ENVIRONMENT -- EXT - FCPATH - SELF - BASEPATH - APPPATH +- VIEWPATH - CI_VERSION - FILE_READ_MODE - FILE_WRITE_MODE @@ -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 45950fc11..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 @@ -47,31 +47,40 @@ segment of the URL, and a number is found in the second segment, the You can match literal values or you can use two wildcard types: **(:num)** will match a segment containing only numbers. - **(:any)** will match a segment containing any character. +**(:any)** will match a segment containing any character (except for '/', which is the segment delimiter). + +.. note:: Wildcards are actually aliases for regular expressions, with + **:any** being translated to **[^/]+** and **:num** to **[0-9]+**, + respectively. .. note:: Routes will run in the order they are defined. Higher routes will always take precedence over lower ones. +.. note:: Route rules are not filters! Setting a rule of e.g. + 'foo/bar/(:num)' will not prevent controller *Foo* and method + *bar* to be called with a non-numeric value if that is a valid + route. + 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" @@ -79,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. @@ -99,12 +108,39 @@ rules. Any valid regular expression is allowed, as are back-references. A typical RegEx route might look something like this:: - $route['products/([a-z]+)/(\d+)'] = "$1/id_$2"; + $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 function. +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 +multiple segments. +For example, if a user accesses a password protected area of your web +application and you wish to be able to redirect them back to the same +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, +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 +more about them, `regular-expressions.info <http://www.regular-expressions.info/>` +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:: -You can also mix and match wildcards with regular expressions. + $route['products/([a-z]+)/edit/(\d+)'] = function ($product_type, $id) + { + return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id; + }; Reserved Routes =============== @@ -125,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..99bc056f7 100644 --- a/user_guide_src/source/general/styleguide.rst +++ b/user_guide_src/source/general/styleguide.rst @@ -52,7 +52,7 @@ whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should **OMIT** the closing PHP tag, and instead use a comment block to mark the end of file and -it's location relative to the application root. This allows you to still +its location relative to the application root. This allows you to still identify a file as being complete and not truncated. **INCORRECT**:: @@ -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 48095a11d..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,28 +84,24 @@ 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, Â captcha_time int(10) unsigned NOT NULL, Â - ip_address varchar(16) default '0' NOT NULL, Â + ip_address varchar(45) NOT NULL, Â word varchar(20) NOT NULL, Â PRIMARY KEY `captcha_id` (`captcha_id`), Â KEY `word` (`word`) ); 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 e332a913f..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,54 +264,79 @@ 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() =============== +.. php:function:: days_in_month($month = 0, $year = '') + + :param int $month: a numeric month + :param int $year: a numeric year + :returns: int + Returns the number of days in a given month/year. Takes leap years into account. -.. php:method:: days_in_month($month = 0, $year = '') +Example:: - :param integer $month: a numeric month - :param integer $year: a numeric year - :returns: integer + echo days_in_month(06, 2005); -Example +If the second parameter is empty, the current year will be used. -:: +date_range() +============ - echo days_in_month(06, 2005); +.. php:function:: date_range($unix_start = '', $mixed = '', $is_unix = TRUE, $format = 'Y-m-d') -If the second parameter is empty, the current year will be used. + :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 + +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:"; + foreach ($range as $date) + { + echo $date."\n"; + } 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 @@ -385,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'); @@ -421,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 @@ -459,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..860c568b9 100644 --- a/user_guide_src/source/helpers/download_helper.rst +++ b/user_guide_src/source/helpers/download_helper.rst @@ -9,34 +9,42 @@ 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 mixed $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 second parameter to NULL and ``$filename`` is an existing, readable +file path, then its content will be read instead. -:: +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 - -:: - - $data = file_get_contents("/path/to/photo.jpg"); // Read the file's contents - $name = 'myphoto.jpg'; - force_download($name, $data); +do the following:: + // Contents of photo.jpg will be automatically read + force_download('/path/to/photo.jpg', NULL);
\ 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 fa7b3dbf9..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. + +Here's a simple example:: 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 - -:: +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() -============= - -Lets you generate a standard submit button. Simple example +.. php:function:: form_radio($data = '', $value = '', $checked = FALSE, $extra = '') -:: - - echo form_submit('mysubmit', 'Submit Post!'); - // Would produce: <input type="submit" name="mysubmit" value="Submit Post!" /> + :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 -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,77 +471,110 @@ 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 +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 - -:: +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); ?>" /> @@ -489,29 +585,42 @@ safely 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> @@ -522,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'); ?> /> @@ -535,15 +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.
\ No newline at end of file +.. 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. + +form_error() +============ + +.. php:function:: form_error($field = '', $prefix = '', $suffix = '') + + :param string $field: Field name + :param string $prefix: Error opening tag + :param string $suffix: Error closing tag + :returns: 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. + +Example:: + + // Assuming that the 'username' field value was incorrect: + echo form_error('myfield', '<div class="error">', '</div>'); + + // 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..1911e3bfd 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() +====== -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 +.. php:function:: lang($line, $for = '', $attributes = array()) -:: + :param string $line: Language line key + :param string $for: HTML "for" attribute (ID of the element we're creating a label for) + :param array $attributes: Any additional HTML attributes + :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 +``CI_Lang::line()``. - echo lang('language_key', 'form_item_id'); - // becomes <label for="form_item_id">language_key</label> +Example:: + echo lang('language_key', 'form_item_id', array('class' => 'myClass'); + // Outputs: <label for="form_item_id" class="myClass">Language line</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 19500aa0d..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,21 +98,34 @@ 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. +.. note:: This function is DEPRECATED. Use the native ``str_repeat()`` + instead. + 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" @@ -110,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?', @@ -128,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"" @@ -189,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 82db6a5b3..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,112 +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 -:: +Creates a standard HTML e-mail link. Usage example:: echo mailto('me@my-site.com', 'Click Here to Contact Me'); -As with the anchor() tab above, you can set attributes using the third -parameter. +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); 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. -:: +Pass the URL string to the function like this:: - $url = "example.com"; - $url = prep_url($url); + $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 Windows 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) { Â Â Â Â Â @@ -319,4 +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* + method won't detect IIS, in that case it is advised you explicitly + 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/images/ci_quick_ref.png b/user_guide_src/source/images/ci_quick_ref.png Binary files differdeleted file mode 100644 index c07d6b469..000000000 --- a/user_guide_src/source/images/ci_quick_ref.png +++ /dev/null diff --git a/user_guide_src/source/images/codeigniter_1.7.1_helper_reference.pdf b/user_guide_src/source/images/codeigniter_1.7.1_helper_reference.pdf Binary files differdeleted file mode 100644 index baec6bcfb..000000000 --- a/user_guide_src/source/images/codeigniter_1.7.1_helper_reference.pdf +++ /dev/null diff --git a/user_guide_src/source/images/codeigniter_1.7.1_helper_reference.png b/user_guide_src/source/images/codeigniter_1.7.1_helper_reference.png Binary files differdeleted file mode 100644 index 15a7c1576..000000000 --- a/user_guide_src/source/images/codeigniter_1.7.1_helper_reference.png +++ /dev/null diff --git a/user_guide_src/source/images/codeigniter_1.7.1_library_reference.pdf b/user_guide_src/source/images/codeigniter_1.7.1_library_reference.pdf Binary files differdeleted file mode 100644 index 312d020eb..000000000 --- a/user_guide_src/source/images/codeigniter_1.7.1_library_reference.pdf +++ /dev/null diff --git a/user_guide_src/source/images/codeigniter_1.7.1_library_reference.png b/user_guide_src/source/images/codeigniter_1.7.1_library_reference.png Binary files differdeleted file mode 100644 index 554ae2eed..000000000 --- a/user_guide_src/source/images/codeigniter_1.7.1_library_reference.png +++ /dev/null diff --git a/user_guide_src/source/index.rst b/user_guide_src/source/index.rst index e42425bab..09bf770fc 100644 --- a/user_guide_src/source/index.rst +++ b/user_guide_src/source/index.rst @@ -37,7 +37,6 @@ Introduction - :doc:`overview/getting_started` - :doc:`overview/at_a_glance` -- :doc:`overview/cheatsheets` - :doc:`overview/features` - :doc:`overview/appflow` - :doc:`overview/mvc` @@ -80,6 +79,7 @@ Driver Reference - :doc:`libraries/caching` - :doc:`database/index` - :doc:`libraries/javascript` +- :doc:`libraries/sessions` **************** Helper Reference @@ -118,5 +118,4 @@ Contributing to CodeIgniter database/index documentation/index tutorial/index - general/quick_reference - general/credits
\ No newline at end of file + general/credits diff --git a/user_guide_src/source/installation/upgrade_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 f304a716f..ff601867e 100644 --- a/user_guide_src/source/installation/upgrade_300.rst +++ b/user_guide_src/source/installation/upgrade_300.rst @@ -31,36 +31,161 @@ 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 5: Convert your Session usage from library to driver +********************************************************* + +When you load (or autoload) the Session library, you must now load it as a driver instead of a library. This means +calling ``$this->load->driver('session')`` instead of ``$this->load->library('session')`` and/or listing 'session' +in ``$autoload['drivers']`` instead of ``$autoload['libraries']``. + +With the change from a single Session Library to the new Session Driver, two new config items have been added: + + - ``$config['sess_driver']`` selects which driver to initially load. Options are: + - 'cookie' (the default) for classic CodeIgniter cookie-based sessions + - 'native' for native PHP Session support + - the name of a custom driver you have provided (see :doc:`Session Driver <../libraries/sessions>` for more info) + - ``$config['sess_valid_drivers']`` provides an array of additional custom drivers to make available for loading + +As the new Session Driver library loads the classic Cookie driver by default and always makes 'cookie' and 'native' +available as valid drivers, neither of these configuration items are required. However, it is recommended that you +add them for clarity and ease of configuration in the future. + +If you have written a Session extension, you must move it into a 'Session' sub-directory of 'libraries', following the +standard for Drivers. Also beware that some functions which are not part of the external Session API have moved into +the drivers, so your extension may have to be broken down into separate library and driver class extensions. + *************************************** -Step 4: 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 -need to rename the `$active_record` variable to `$query_builder`. +need to rename the `$active_record` variable to `$query_builder` +:: - $active_group = 'default'; - // $active_record = TRUE; - $query_builder = TRUE; + $active_group = 'default'; + // $active_record = TRUE; + $query_builder = TRUE; ******************************* -Step 5: 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 8: Update your config/routes.php containing (:any) +******************************************************* + +Historically, CodeIgniter has always provided the **:any** wildcard in routing, +with the intention of providing a way to match any character **within** an URI segment. + +However, the **:any** wildcard is actually just an alias for a regular expression +and used to be executed in that manner as **.+**. This is considered a bug, as it +also matches the / (forward slash) character, which is the URI segment delimiter +and that was never the intention. In CodeIgniter 3, the **:any** wildcard will now +represent **[^/]+**, so that it will not match a forward slash. + +There are certainly many developers that have utilized this bug as an actual feature. +If you're one of them and want to match a forward slash, please use the **.+** +regular expression:: + + (.+) // matches ANYTHING + (:any) // matches any character, except for '/' + + **************************************************************************** -Step 6: 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 7: Remove usage of (previously) deprecated functionalities -*************************************************************** +************************************************************* +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, +pass FALSE as the first parameter in the ``send()`` method: + +:: + + if ($this->email->send(FALSE)) + { + // Parameters won't be cleared + } + +*************************************************** +Step 12: Update your Form_validation language lines +*************************************************** + +Two improvements have been made to the :doc:`Form Validation Library +<../libraries/form_validation>`'s :doc:`language <../libraries/language>` +files and error messages format: + + - :doc:`Language Library <../libraries/language>` line keys now must be + prefixed with **form_validation_** in order to avoid collisions:: + + // Old + $lang['rule'] = ... + + // New + $lang['form_validation_rule'] = ... + + - The error messages format has been changed to use named parameters, to + allow more flexibility than what `sprintf()` offers:: + + // Old + 'The %s field does not match the %s field.' + + // New + 'The {field} field does not match the {param} field.' -In addition to the ``$autoload['core']`` configuration setting, there's a number of other functionalities -that have been removed in CodeIgniter 3.0.0: +.. note:: The old formatting still works, but the non-prefixed line keys + are DEPRECATED and scheduled for removal in CodeIgniter 3.1+. + Therefore you're encouraged to update its usage sooner rather than + later. + +**************************************************************** +Step 13: Remove usage of (previously) deprecated functionalities +**************************************************************** + +In addition to the ``$autoload['core']`` configuration setting, there's a +number of other functionalities that have been removed in CodeIgniter 3.0.0: The SHA1 library ================ @@ -102,6 +227,40 @@ CodeIgniter 3.1+. .. note:: This function is still available, but you're strongly encouraged to remove it's usage sooner rather than later. +String helper repeater() +======================== + +: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. + +String helper trim_slashes() +============================ + +: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() =========================== @@ -138,4 +297,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.
\ No newline at end of file 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/caching.rst b/user_guide_src/source/libraries/caching.rst index 2f06d29f9..8d7b4c440 100644 --- a/user_guide_src/source/libraries/caching.rst +++ b/user_guide_src/source/libraries/caching.rst @@ -32,6 +32,17 @@ available in the hosting environment. echo $foo; +You can also prefix cache item names via the **key_prefix** setting, which is useful +to avoid collisions when you're running multiple applications on the same environment. + +:: + + $this->load->driver('cache', + array('adapter' => 'apc', 'backup' => 'file', 'key_prefix' => 'my_') + ); + + $this->cache->get('foo'); // Will get the cache entry named 'my_foo' + ****************** Function Reference ****************** @@ -39,7 +50,7 @@ Function Reference .. php:class:: CI_Cache is_supported() -=============== +============== .. php:method:: is_supported ( $driver ) @@ -130,7 +141,7 @@ clean() $this->cache->clean(); cache_info() -============= +============ .. php:method:: cache_info ( ) @@ -148,7 +159,7 @@ cache_info() get_metadata() -=============== +============== .. php:method:: get_metadata ( $id ) @@ -166,7 +177,6 @@ get_metadata() .. note:: The information returned and the structure of the data is dependent on which adapter is being used. - ******* Drivers ******* @@ -181,7 +191,7 @@ specific adapter to the driver loader as follows:: $this->cache->apc->save('foo', 'bar', 10); For more information on APC, please see -`http://php.net/apc <http://php.net/apc>`_ +`http://php.net/apc <http://php.net/apc>`_. File-based Caching ================== @@ -201,20 +211,49 @@ Memcached Caching ================= Multiple Memcached servers can be specified in the memcached.php -configuration file, located in the application/config/ directory. +configuration file, located in the _application/config/* directory. -All of the functions listed above can be accessed without passing a +All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:: $this->load->driver('cache'); $this->cache->memcached->save('foo', 'bar', 10); For more information on Memcached, please see -`http://php.net/memcached <http://php.net/memcached>`_ +`http://php.net/memcached <http://php.net/memcached>`_. + +WinCache Caching +================ + +Under Windows, you can also utilize the WinCache driver. + +All of the functions listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->wincache->save('foo', 'bar', 10); + +For more information on WinCache, please see +`http://php.net/wincache <http://php.net/wincache>`_. + +Redis Caching +============= + +All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->redis->save('foo', 'bar', 10); + +.. important:: Redis may require one or more of the following options: + **host**, **post**, **timeout**, **password**. + +The Redis PHP extension repository is located at +`https://github.com/nicolasff/phpredis <https://github.com/nicolasff/phpredis>`_. Dummy Cache =========== This is a caching backend that will always 'miss.' It stores no data, but lets you keep your caching code in place in environments that don't -support your chosen cache. +support your chosen cache.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/cart.rst b/user_guide_src/source/libraries/cart.rst index 6594b3b9a..716e94bcb 100644 --- a/user_guide_src/source/libraries/cart.rst +++ b/user_guide_src/source/libraries/cart.rst @@ -279,16 +279,22 @@ by which this is returned by passing it "true" where the contents will be sorted from newest to oldest, by leaving this function blank, you'll automatically just get first added to the basket to last added to the basket. -$this->cart->has_options(rowid); -******************************** +$this->cart->get_item($row_id); +******************************* + +Returns an array containing data for the item matching the specified row ID, +or FALSE if no such item exists. + +$this->cart->has_options($row_id); +********************************** Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above. -$this->cart->product_options(rowid); -************************************ +$this->cart->product_options($row_id); +************************************** Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart->contents(), since you diff --git a/user_guide_src/source/libraries/email.rst b/user_guide_src/source/libraries/email.rst index c5fa68004..8643444f8 100644 --- a/user_guide_src/source/libraries/email.rst +++ b/user_guide_src/source/libraries/email.rst @@ -97,7 +97,7 @@ Preference Default Value Options Descript **mailtype** text text or html Type of mail. If you send HTML email you must send it as a complete web page. Make sure you don't have any relative links or relative image paths otherwise they will not work. -**charset** utf-8 Character set (utf-8, iso-8859-1, etc.). +**charset** ``$config['charset']`` Character set (utf-8, iso-8859-1, etc.). **validate** FALSE TRUE or FALSE (boolean) Whether to validate the email address. **priority** 3 1, 2, 3, 4, 5 Email Priority. 1 = highest. 5 = lowest. 3 = normal. **crlf** \\n "\\r\\n" or "\\n" or "\\r" Newline character. (Use "\\r\\n" to comply with RFC 822). @@ -117,6 +117,13 @@ Sets the email address and name of the person sending the email:: $this->email->from('you@example.com', 'Your Name'); +You can also set a Return-Path, to help redirect undelivered mail:: + + $this->email->from('you@example.com', 'Your Name', 'returned_emails@example.com'); + +.. note:: Return-Path can't be used if you've configured + 'smtp' as your protocol. + $this->email->reply_to() ------------------------- @@ -226,6 +233,14 @@ success or failure, enabling it to be used conditionally:: // Generate error } +This function will automatically clear all parameters if the request was +successful. To stop this behaviour pass FALSE:: + + if ($this->email->send(FALSE)) + { + // Parameters won't be cleared + } + $this->email->attach() ---------------------- @@ -253,11 +268,21 @@ parameter as mime-type:: $this->email->attach($buffer, 'attachment', 'report.pdf', 'application/pdf'); $this->email->print_debugger() -------------------------------- +------------------------------ Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging. +You can optionally specify which parts of the message should be printed. +Valid options are: **headers**, **subject**, **body**. + +Example:: + + // Will only print the email headers, excluding the message subject and body + $this->email->print_debugger(array('headers')); + +.. note:: By default, all of the raw data will be printed. + Overriding Word Wrapping ======================== diff --git a/user_guide_src/source/libraries/file_uploading.rst b/user_guide_src/source/libraries/file_uploading.rst index 65cd5c722..c7965ae11 100644 --- a/user_guide_src/source/libraries/file_uploading.rst +++ b/user_guide_src/source/libraries/file_uploading.rst @@ -26,7 +26,7 @@ Creating the Upload Form ======================== Using a text editor, create a form called upload_form.php. In it, place -this code and save it to your applications/views/ folder:: +this code and save it to your **application/views/** directory:: <html> <head> @@ -59,7 +59,7 @@ The Success Page ================ Using a text editor, create a form called upload_success.php. In it, -place this code and save it to your applications/views/ folder:: +place this code and save it to your **application/views/** directory:: <html> <head> @@ -84,7 +84,7 @@ The Controller ============== Using a text editor, create a controller called upload.php. In it, place -this code and save it to your applications/controllers/ folder:: +this code and save it to your **application/controllers/** directory:: <?php @@ -127,12 +127,12 @@ this code and save it to your applications/controllers/ folder:: } ?> -The Upload Folder -================= +The Upload Directory +==================== -You'll need a destination folder for your uploaded images. Create a -folder at the root of your CodeIgniter installation called uploads and -set its file permissions to 777. +You'll need a destination directory for your uploaded images. Create a +directory at the root of your CodeIgniter installation called uploads +and set its file permissions to 777. Try it! ======= @@ -153,7 +153,7 @@ Initializing the Upload Class ============================= Like most other classes in CodeIgniter, the Upload class is initialized -in your controller using the $this->load->library function:: +in your controller using the ``$this->load->library()`` method:: $this->load->library('upload'); @@ -175,7 +175,7 @@ following preferences:: $this->load->library('upload', $config); - // Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class: + // Alternately you can set preferences by calling the ``initialize()`` method. Useful if you auto-load the class: $this->upload->initialize($config); The above preferences should be fairly self-explanatory. Below is a @@ -190,22 +190,27 @@ what will be used if you do not specify that preference. ============================ ================= ======================= ====================================================================== Preference Default Value Options Description ============================ ================= ======================= ====================================================================== -**upload_path** None None The path to the folder where the upload should be placed. The folder - must be writable and the path can be absolute or relative. +**upload_path** None None The path to the directory where the upload should be placed. The + directory must be writable and the path can be absolute or relative. **allowed_types** None None The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Separate multiple types with a pipe. **file_name** None Desired file name If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. + If no extension is provided in the original file_name will be used. **overwrite** FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists. **max_size** 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default. -**max_width** 0 None The maximum width (in pixels) that the file can be. Set to zero for no +**max_width** 0 None The maximum width (in pixels) that the image can be. Set to zero for no limit. -**max_height** 0 None The maximum height (in pixels) that the file can be. Set to zero for no +**max_height** 0 None The maximum height (in pixels) that the image can be. Set to zero for no + limit. +**min_width** 0 None The minimum width (in pixels) that the image can be. Set to zero for no + limit. +**min_height** 0 None The minimum height (in pixels) that the image can be. Set to zero for no limit. **max_filename** 0 None The maximum length that a file name can be. Set to zero for no limit. **max_filename_increment** 100 None When overwrite is set to FALSE, use this to set the maximum filename @@ -226,42 +231,46 @@ Setting preferences in a config file If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the upload.php, add the $config array in that file. Then save the file in: -config/upload.php and it will be used automatically. You will NOT need -to use the $this->upload->initialize function if you save your +**config/upload.php** and it will be used automatically. You will NOT +need to use the ``$this->upload->initialize()`` method if you save your preferences in a config file. -****************** -Function Reference -****************** +*************** +Class Reference +*************** -The following functions are available +The following methods are available: $this->upload->do_upload() -=========================== +========================== + +Performs the upload based on the preferences you've set. + +.. note:: By default the upload routine expects the file to come from + a form field called userfile, and the form must be of type + "multipart". -Performs the upload based on the preferences you've set. Note: By -default the upload routine expects the file to come from a form field -called userfile, and the form must be a "multipart type:: +:: <form method="post" action="some_action" enctype="multipart/form-data" /> If you would like to set your own field name simply pass its value to -the do_upload function:: +the ``do_upload()`` method:: $field_name = "some_field_name"; $this->upload->do_upload($field_name); $this->upload->display_errors() -================================ +=============================== -Retrieves any error messages if the do_upload() function returned -false. The function does not echo automatically, it returns the data so +Retrieves any error messages if the ``do_upload()`` method returned +false. The method does not echo automatically, it returns the data so you can assign it however you need. Formatting Errors ***************** -By default the above function wraps any errors within <p> tags. You can +By default the above method wraps any errors within <p> tags. You can set your own delimiters like this:: $this->upload->display_errors('<p>', '</p>'); @@ -269,25 +278,25 @@ set your own delimiters like this:: $this->upload->data() ===================== -This is a helper function that returns an array containing all of the +This is a helper method that returns an array containing all of the data related to the file you uploaded. Here is the array prototype:: Array ( - [file_name] => mypic.jpg - [file_type] => image/jpeg - [file_path] => /path/to/your/upload/ - [full_path] => /path/to/your/upload/jpg.jpg - [raw_name] => mypic - [orig_name] => mypic.jpg - [client_name] => mypic.jpg - [file_ext] => .jpg - [file_size] => 22.2 - [is_image] => 1 - [image_width] => 800 - [image_height] => 600 - [image_type] => jpeg - [image_size_str] => width="800" height="200" + [file_name] => mypic.jpg + [file_type] => image/jpeg + [file_path] => /path/to/your/upload/ + [full_path] => /path/to/your/upload/jpg.jpg + [raw_name] => mypic + [orig_name] => mypic.jpg + [client_name] => mypic.jpg + [file_ext] => .jpg + [file_size] => 22.2 + [is_image] => 1 + [image_width] => 800 + [image_height] => 600 + [image_type] => jpeg + [image_size_str] => width="800" height="200" ) To return one element from the array:: @@ -331,4 +340,4 @@ Image height Image type. Typically the file extension without the period. **image_size_str** A string containing the width and height. Useful to put into an image -tag. +tag.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst index 3bcad7ba6..fbe540ce0 100644 --- a/user_guide_src/source/libraries/form_validation.rst +++ b/user_guide_src/source/libraries/form_validation.rst @@ -53,7 +53,7 @@ In order to implement form validation you'll need three things: #. A :doc:`View <../general/views>` file containing a form. #. A View file containing a "success" message to be displayed upon successful submission. -#. A :doc:`controller <../general/controllers>` function to receive and +#. A :doc:`controller <../general/controllers>` method to receive and process the submitted data. Let's create those three things, using a member sign-up form as the @@ -63,7 +63,7 @@ The Form ======== Using a text editor, create a form called myform.php. In it, place this -code and save it to your applications/views/ folder:: +code and save it to your application/views/ folder:: <html> <head> @@ -98,7 +98,7 @@ The Success Page ================ Using a text editor, create a form called formsuccess.php. In it, place -this code and save it to your applications/views/ folder:: +this code and save it to your application/views/ folder:: <html> <head> @@ -117,7 +117,7 @@ The Controller ============== Using a text editor, create a controller called form.php. In it, place -this code and save it to your applications/controllers/ folder:: +this code and save it to your application/controllers/ folder:: <?php @@ -139,7 +139,6 @@ this code and save it to your applications/controllers/ folder:: } } } - ?> Try it! ======= @@ -152,7 +151,7 @@ If you submit the form you should simply see the form reload. That's because you haven't set up any validation rules yet. **Since you haven't told the Form Validation class to validate anything -yet, it returns FALSE (boolean false) by default. The run() function +yet, it returns FALSE (boolean false) by default. ``The run()`` method only returns TRUE if it has successfully applied your rules without any of them failing.** @@ -176,7 +175,7 @@ The form (myform.php) is a standard web form with a couple exceptions: This function will return any error messages sent back by the validator. If there are no messages it returns an empty string. -The controller (form.php) has one function: index(). This function +The controller (form.php) has one method: ``index()``. This method initializes the validation class and loads the form helper and URL helper used by your view files. It also runs the validation routine. Based on whether the validation was successful it either presents the @@ -190,11 +189,11 @@ Setting Validation Rules CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you -will use the set_rules() function:: +will use the ``set_rules()`` method:: $this->form_validation->set_rules(); -The above function takes **three** parameters as input: +The above method takes **three** parameters as input: #. The field name - the exact name you've given the form field. #. A "human" name for this field, which will be inserted into the error @@ -202,11 +201,11 @@ The above function takes **three** parameters as input: a human name of "Username". #. The validation rules for this form field. -.. note:: If you would like the field - name to be stored in a language file, please see :ref:`translating-field-names`. +.. note:: If you would like the field name to be stored in a language + file, please see :ref:`translating-field-names`. Here is an example. In your controller (form.php), add this code just -below the validation initialization function:: +below the validation initialization method:: $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); @@ -240,7 +239,6 @@ Your controller should now look like this:: } } } - ?> Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you'll @@ -252,32 +250,32 @@ see your success page. Setting Rules Using an Array ============================ -Before moving on it should be noted that the rule setting function can +Before moving on it should be noted that the rule setting method can be passed an array if you prefer to set all your rules in one action. If -you use this approach you must name your array keys as indicated:: +you use this approach, you must name your array keys as indicated:: $config = array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'Password Confirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ); + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); $this->form_validation->set_rules($config); @@ -285,13 +283,12 @@ Cascading Rules =============== CodeIgniter lets you pipe multiple rules together. Let's try it. Change -your rules in the third parameter of rule setting function, like this:: +your rules in the third parameter of rule setting method, 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: @@ -304,32 +301,33 @@ Give it a try! Submit your form without the proper data and you'll see new error messages that correspond to your new rules. There are numerous rules available which you can read about in the validation reference. -.. note:: You can also pass an array of rules to set_rules(), instead of a string. Example:: +.. note:: You can also pass an array of rules to ``set_rules()``, + instead of a string. Example:: $this->form_validation->set_rules('username', 'Username', array('required', 'min_length[5]')); Prepping Data ============= -In addition to the validation functions like the ones we used above, you +In addition to the validation method like the ones we used above, you can also prep your data in various ways. For example, you can set up rules like this:: $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean'); - $this->form_validation->set_rules('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 -password to MD5, and running the username through the "xss_clean" -function, which removes malicious data. +password to MD5, and running the username through the `xss_clean()` +method, which removes malicious data. **Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, md5, etc.** .. note:: You will generally want to use the prepping functions - **after** the validation rules so if there is an error, the original - data will be shown in the form. + **after** the validation rules so if there is an error, the + original data will be shown in the form. Re-populating the form ====================== @@ -342,9 +340,9 @@ commonly is:: set_value('field name') Open your myform.php view file and update the **value** in each field -using the set_value() function: +using the ``set_value()`` function: -**Don't forget to include each field name in the set_value() +**Don't forget to include each field name in the ``set_value()`` functions!** :: @@ -381,9 +379,9 @@ functions!** Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated -.. note:: The :ref:`function-reference` section below - contains functions that permit you to re-populate <select> menus, radio - buttons, and checkboxes. +.. note:: The :ref:`class-reference` section below + contains functions that permit you to re-populate <select> menus, + radio buttons, and checkboxes. **Important Note:** If you use an array as the name of a form field, you must supply it as an array to the function. Example:: @@ -392,20 +390,20 @@ must supply it as an array to the function. Example:: For more info please see the :ref:`using-arrays-as-field-names` section below. -Callbacks: Your own Validation Functions -======================================== +Callbacks: Your own Validation Methods +====================================== The validation system supports callbacks to your own validation -functions. This permits you to extend the validation class to meet your +methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the -user is choosing a unique username, you can create a callback function -that does that. Let's create a example of this. +user is choosing a unique username, you can create a callback method +that does that. Let's create an example of this. In your controller, change the "username" rule to this:: $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); -Then add a new function called username_check to your controller. +Then add a new method called ``username_check()`` to your controller. Here's how your controller should now look:: <?php @@ -433,11 +431,11 @@ Here's how your controller should now look:: } } - public function username_check($str) + protected function username_check($str) { if ($str == 'test') { - $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); + $this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"'); return FALSE; } else @@ -447,17 +445,16 @@ Here's how your controller should now look:: } } - ?> Reload your form and submit it with the word "test" as the username. You -can see that the form field data was passed to your callback function +can see that the form field data was passed to your callback method for you to process. -To invoke a callback just put the function name in a rule, with +To invoke a callback just put the method name in a rule, with "callback\_" as the rule **prefix**. If you need to receive an extra -parameter in your callback function, just add it normally after the -function name between square brackets, as in: "callback_foo**[bar]**", -then it will be passed as the second argument of your callback function. +parameter in your callback method, just add it normally after the +method name between square brackets, as in: "callback_foo**[bar]**", +then it will be passed as the second argument of your callback method. .. note:: You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a @@ -470,28 +467,33 @@ Setting Error Messages ====================== All of the native error messages are located in the following language -file: language/english/form_validation_lang.php +file: **system/language/english/form_validation_lang.php** To set your own custom message you can either edit that file, or use the -following function:: +following method:: $this->form_validation->set_message('rule', 'Error Message'); Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed. -If you include %s in your error string, it will be replaced with the -"human" name you used for your field when you set your rules. +If you'd like to include a field's "human" name, or the optional +parameter some rules allow for (such as max_length), you can add the +**{field}** and **{param}** tags to your message, respectively. -In the "callback" example above, the error message was set by passing -the name of the function:: + $this->form_validation->set_message('min_length', '{field} must have at least {param} characters.'); - $this->form_validation->set_message('username_check') +On a field with the human name Username and a rule of min_length[5], an +error would display: "Username must have at least 5 characters." -You can also override any error message found in the language file. For -example, to change the message for the "required" rule you will do this:: +.. note:: The old `sprintf()` method of using **%s** in your error messages + will still work, however it will override the tags above. You should + use one or the other. - $this->form_validation->set_message('required', 'Your custom message here'); +In the callback rule example above, the error message was set by passing +the name of the method (without the "callback_" prefix):: + + $this->form_validation->set_message('username_check') .. _translating-field-names: @@ -499,10 +501,10 @@ Translating Field Names ======================= If you would like to store the "human" name you passed to the -set_rules() function in a language file, and therefore make the name +``set_rules()`` method in a language file, and therefore make the name able to be translated, here's how: -First, prefix your "human" name with lang:, as in this example:: +First, prefix your "human" name with **lang:**, as in this example:: $this->form_validation->set_rules('first_name', 'lang:first_name', 'required'); @@ -530,7 +532,7 @@ each error message shown. You can either change these delimiters globally, individually, or change the defaults in a config file. #. **Changing delimiters Globally** - To globally change the error delimiters, in your controller function, + To globally change the error delimiters, in your controller method, just after loading the Form Validation class, add this:: $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); @@ -549,16 +551,15 @@ globally, individually, or change the defaults in a config file. #. **Set delimiters in a config file** You can add your error delimiters in application/config/form_validation.php as follows:: - + $config['error_prefix'] = '<div class="error_prefix">'; $config['error_suffix'] = '</div>'; - Showing Errors Individually =========================== If you prefer to show an error message next to each form field, rather -than as a list, you can use the form_error() function. +than as a list, you can use the ``form_error()`` function. Try it! Change your form so that it looks like this:: @@ -581,8 +582,8 @@ Try it! Change your form so that it looks like this:: If there are no errors, nothing will be shown. If there is an error, the message will appear. -**Important Note:** If you use an array as the name of a form field, you -must supply it as an array to the function. Example:: +.. important:: If you use an array as the name of a form field, you + must supply it as an array to the function. Example:: <?php echo form_error('options[size]'); ?> <input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /> @@ -592,25 +593,26 @@ For more info please see the :ref:`using-arrays-as-field-names` section below. Validating an Array (other than $_POST) ======================================= -Sometimes you may want to validate an array that does not originate from $_POST data. +Sometimes you may want to validate an array that does not originate from ``$_POST`` data. In this case, you can specify the array to be validated:: - + $data = array( - 'username' => 'johndoe', - 'password' => 'mypassword', - 'passconf' => 'mypassword' - ); + 'username' => 'johndoe', + 'password' => 'mypassword', + 'passconf' => 'mypassword' + ); $this->form_validation->set_data($data); -Creating validation rules, running the validation and retrieving error messages works the same whether you are -validating $_POST data or an array. +Creating validation rules, running the validation, and retrieving error messages works the +same whether you are validating ``$_POST`` data or an array. -**Important Note:** If you want to validate more than one array during a single execution, then you should -call the reset_validation() function before setting up rules and validating the new array. +.. important:: If you want to validate more than one array during a single + execution, then you should call the ``reset_validation()`` method + before setting up rules and validating the new array. -For more info please see the :ref:`function-reference` section below. +For more info please see the :ref:`class-reference` section below. .. _saving-groups: @@ -621,7 +623,7 @@ Saving Sets of Validation Rules to a Config File A nice feature of the Form Validation class is that it permits you to store all your validation rules for your entire application in a config file. You can organize these rules into "groups". These groups can -either be loaded automatically when a matching controller/function is +either be loaded automatically when a matching controller/method is called, or you can manually call each set as needed. How to save your rules @@ -633,32 +635,32 @@ you will place an array named $config with your rules. As shown earlier, the validation array will have this prototype:: $config = array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'Password Confirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ); + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); Your validation rule file will be loaded automatically and used when you -call the run() function. +call the ``run()`` method. -Please note that you MUST name your array $config. +Please note that you MUST name your ``$config`` array. Creating Sets of Rules ====================== @@ -669,126 +671,125 @@ rules. We've arbitrarily called these two rules "signup" and "email". You can name your rules anything you want:: $config = array( - 'signup' => array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'PasswordConfirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ), - 'email' => array( - array( - 'field' => 'emailaddress', - 'label' => 'EmailAddress', - 'rules' => 'required|valid_email' - ), - array( - 'field' => 'name', - 'label' => 'Name', - 'rules' => 'required|alpha' - ), - array( - 'field' => 'title', - 'label' => 'Title', - 'rules' => 'required' - ), - array( - 'field' => 'message', - 'label' => 'MessageBody', - 'rules' => 'required' - ) - ) - ); + 'signup' => array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ), + 'email' => array( + array( + 'field' => 'emailaddress', + 'label' => 'EmailAddress', + 'rules' => 'required|valid_email' + ), + array( + 'field' => 'name', + 'label' => 'Name', + 'rules' => 'required|alpha' + ), + array( + 'field' => 'title', + 'label' => 'Title', + 'rules' => 'required' + ), + array( + 'field' => 'message', + 'label' => 'MessageBody', + 'rules' => 'required' + ) + ) + ); Calling a Specific Rule Group ============================= -In order to call a specific group you will pass its name to the run() -function. For example, to call the signup rule you will do this:: +In order to call a specific group, you will pass its name to the ``run()`` +method. For example, to call the signup rule you will do this:: if ($this->form_validation->run('signup') == FALSE) { - $this->load->view('myform'); + $this->load->view('myform'); } else { - $this->load->view('formsuccess'); + $this->load->view('formsuccess'); } -Associating a Controller Function with a Rule Group -=================================================== +Associating a Controller Method with a Rule Group +================================================= An alternate (and more automatic) method of calling a rule group is to -name it according to the controller class/function you intend to use it +name it according to the controller class/method you intend to use it with. For example, let's say you have a controller named Member and a -function named signup. Here's what your class might look like:: +method named signup. Here's what your class might look like:: <?php class Member extends CI_Controller { - function signup() - { - $this->load->library('form_validation'); - - if ($this->form_validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } - } + public function signup() + { + $this->load->library('form_validation'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } } - ?> In your validation config file, you will name your rule group member/signup:: $config = array( - 'member/signup' => array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'PasswordConfirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ) - ); - -When a rule group is named identically to a controller class/function it -will be used automatically when the run() function is invoked from that -class/function. + 'member/signup' => array( + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'PasswordConfirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ) + ); + +When a rule group is named identically to a controller class/method it +will be used automatically when the ``run()`` method is invoked from that +class/method. .. _using-arrays-as-field-names: @@ -861,8 +862,10 @@ Rule Parameter Description ========================= ========== ============================================================================================= ======================= **required** No Returns FALSE if the form element is empty. **matches** Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item] -**is_unique** Yes Returns FALSE if the form element is not unique to the is_unique[table.field] - table and field name in the parameter. is_unique[table.field] +**differs** Yes Returns FALSE if the form element does not differ from the one in the parameter. differs[form_item] +**is_unique** Yes Returns FALSE if the form element is not unique to the table and field name in the is_unique[table.field] + parameter. Note: This rule requires :doc:`Query Builder <../database/query_builder>` to be + enabled in order to work. **max_length** Yes Returns FALSE if the form element is longer then the parameter value. max_length[12] **exact_length** Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8] **greater_than** Yes Returns FALSE if the form element is less than or equal to the parameter value or not greater_than[8] @@ -884,7 +887,7 @@ Rule Parameter Description 0, 1, 2, 3, etc. **is_natural_no_zero** No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc. -**is_unique** Yes Returns FALSE if the form element is not unique in a database table. is_unique[table.field] +**valid_url** No Returns FALSE if the form element does not contain a valid URL. **valid_email** No Returns FALSE if the form element does not contain a valid email address. **valid_emails** No Returns FALSE if any value provided in a comma separated list is not a valid email. **valid_ip** No Returns FALSE if the supplied IP is not valid. @@ -892,7 +895,7 @@ Rule Parameter Description **valid_base64** No Returns FALSE if the supplied string contains anything other than valid Base64 characters. ========================= ========== ============================================================================================= ======================= -.. note:: These rules can also be called as discrete functions. For +.. note:: These rules can also be called as discrete methods. For example:: $this->form_validation->required($string); @@ -905,35 +908,35 @@ Rule Parameter Description Prepping Reference ****************** -The following is a list of all the prepping functions that are available +The following is a list of all the prepping methods that are available to use: ==================== ========= =================================================================================================== Name Parameter Description ==================== ========= =================================================================================================== -**xss_clean** No Runs the data through the XSS filtering function, described in the :doc:`Input Class <input>` page. +**xss_clean** No Runs the data through the XSS filtering method, described in the :doc:`Input Class <input>` page. **prep_for_form** No Converts special characters so that HTML data can be shown in a form field without breaking it. **prep_url** No Adds "\http://" to URLs if missing. **strip_image_tags** No Strips the HTML from image tags leaving the raw URL. **encode_php_tags** No Converts PHP tags to entities. ==================== ========= =================================================================================================== -.. note:: You can also use any native PHP functions that permit one - parameter, like trim, htmlspecialchars, urldecode, etc. +.. note:: You can also use any native PHP functions that permits one + parameter, like ``trim()``, ``htmlspecialchars()``, ``urldecode()``, + etc. -.. _function-reference: +.. _class-reference: -****************** -Function Reference -****************** +*************** +Class Reference +*************** .. php:class:: Form_validation -The following functions are intended for use in your controller -functions. +The following methods are intended for use in your controller. -$this->form_validation->set_rules(); -====================================== +$this->form_validation->set_rules() +=================================== .. php:method:: set_rules ($field, $label = '', $rules = '') @@ -941,27 +944,27 @@ $this->form_validation->set_rules(); :param string $label: The field label :param mixed $rules: The rules, as a string with rules separated by a pipe "|", or an array or rules. :rtype: Object - + Permits you to set validation rules, as described in the tutorial sections above: - :ref:`setting-validation-rules` - :ref:`saving-groups` -$this->form_validation->run(); -=============================== +$this->form_validation->run() +============================= .. php:method:: run ($group = '') :param string $group: The name of the validation group to run :rtype: Boolean - + Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via - the function, as described in: :ref:`saving-groups` + the method, as described in: :ref:`saving-groups` -$this->form_validation->set_message(); -======================================== +$this->form_validation->set_message() +===================================== .. php:method:: set_message ($lang, $val = '') @@ -971,8 +974,8 @@ $this->form_validation->set_message(); Permits you to set custom error messages. See :ref:`setting-error-messages` -$this->form_validation->set_data(); -======================================== +$this->form_validation->set_data() +================================== .. php:method:: set_data ($data = '') @@ -981,16 +984,16 @@ $this->form_validation->set_data(); Permits you to set an array for validation, instead of using the default $_POST array. -$this->form_validation->reset_validation(); -=========================================== +$this->form_validation->reset_validation() +========================================== - .. php:method:: reset_validation () + .. php:method:: reset_validation () - Permits you to reset the validation when you validate more than one array. - This function should be called before validating each new array. + Permits you to reset the validation when you validate more than one array. + This method should be called before validating each new array. -$this->form_validation->error_array(); -======================================== +$this->form_validation->error_array() +===================================== .. php:method:: error_array () @@ -1009,7 +1012,7 @@ containing your forms. Note that these are procedural functions, so they **do not** require you to prepend them with $this->form_validation. form_error() -============= +============ Shows an individual error message associated with the field name supplied to the function. Example:: @@ -1020,7 +1023,7 @@ The error delimiters can be optionally specified. See the :ref:`changing-delimiters` section above. validation_errors() -==================== +=================== Shows all error messages as a string: Example:: @@ -1030,7 +1033,7 @@ The error delimiters can be optionally specified. See the :ref:`changing-delimiters` section above. set_value() -============ +=========== Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The @@ -1042,7 +1045,7 @@ form. Example:: The above form will show "0" when loaded for the first time. set_select() -============= +============ If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter must contain the name @@ -1059,7 +1062,7 @@ Example:: </select> set_checkbox() -=============== +============== Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second @@ -1070,12 +1073,12 @@ lets you set an item as the default (use boolean TRUE/FALSE). Example:: <input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> /> set_radio() -============ +=========== Permits you to display radio buttons in the state they were submitted. This function is identical to the **set_checkbox()** function above. :: - <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'); ?> /> + <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'); ?> />
\ No newline at end of file diff --git a/user_guide_src/source/libraries/image_lib.rst b/user_guide_src/source/libraries/image_lib.rst index ed6575c62..dcdccbd92 100644 --- a/user_guide_src/source/libraries/image_lib.rst +++ b/user_guide_src/source/libraries/image_lib.rst @@ -91,9 +91,9 @@ error upon failure, like this:: echo $this->image_lib->display_errors(); } -Note: You can optionally specify the HTML formatting to be applied to -the errors, by submitting the opening/closing tags in the function, like -this:: +.. note:: You can optionally specify the HTML formatting to be applied to + the errors, by submitting the opening/closing tags in the function, + like this:: $this->image_lib->display_errors('<p>', '</p>'); @@ -225,8 +225,7 @@ pixels) specifying where to crop, like this:: $config['y_axis'] = '40'; All preferences listed in the table above are available for this -function except these: rotation_angle, width, height, create_thumb, -new_image. +function except these: rotation_angle, create_thumb, new_image. Here's an example showing how you might crop an image:: @@ -243,11 +242,11 @@ Here's an example showing how you might crop an image:: echo $this->image_lib->display_errors(); } -Note: Without a visual interface it is difficult to crop images, so this -function is not very useful unless you intend to build such an -interface. That's exactly what we did using for the photo gallery module -in ExpressionEngine, the CMS we develop. We added a JavaScript UI that -lets the cropping area be selected. +.. note:: Without a visual interface it is difficult to crop images, so this + function is not very useful unless you intend to build such an + interface. That's exactly what we did using for the photo gallery module + in ExpressionEngine, the CMS we develop. We added a JavaScript UI that + lets the cropping area be selected. $this->image_lib->rotate() =========================== @@ -338,8 +337,8 @@ The above example will use a 16 pixel True Type font to create the text bottom/center of the image, 20 pixels from the bottom of the image. .. note:: In order for the image class to be allowed to do any - processing, the image file must have "write" file permissions. For - example, 777. + processing, the image file must have "write" file permissions + For example, 777. Watermarking Preferences ======================== diff --git a/user_guide_src/source/libraries/input.rst b/user_guide_src/source/libraries/input.rst index 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/javascript.rst b/user_guide_src/source/libraries/javascript.rst index d5e09c314..393d4e321 100644 --- a/user_guide_src/source/libraries/javascript.rst +++ b/user_guide_src/source/libraries/javascript.rst @@ -192,7 +192,7 @@ and triggered by a click using the jQuery library's click() event. 'width' => '50%', 'marginLeft' => 125 ); - $this->jquery->click('#trigger', $this->jquery->animate('#note', $params, normal)); + $this->jquery->click('#trigger', $this->jquery->animate('#note', $params, 'normal')); fadeIn() / fadeOut() -------------------- diff --git a/user_guide_src/source/libraries/language.rst b/user_guide_src/source/libraries/language.rst index ec678cd21..d288cd65e 100644 --- a/user_guide_src/source/libraries/language.rst +++ b/user_guide_src/source/libraries/language.rst @@ -10,12 +10,11 @@ containing sets of language files. You can create your own language files as needed in order to display error and other messages in other languages. -Language files are typically stored in your system/language directory. -Alternately you can create a folder called language inside your -application folder and store them there. CodeIgniter will look first in -your application/language directory. If the directory does not exist or -the specified language is not located there CI will instead look in your -global system/language folder. +Language files are typically stored in your **system/language/** directory. +Alternately you can create a directory called language inside your +application folder and store them there. CodeIgniter will always load the +one in **system/language/** first and will then look for an override in +your **application/language/** directory. .. note:: Each language should be stored in its own folder. For example, the English files are located at: system/language/english @@ -23,14 +22,14 @@ global system/language folder. Creating Language Files ======================= -Language files must be named with _lang.php as the file extension. For +Language files must be named with **_lang.php** as the file extension. For example, let's say you want to create a file containing error messages. You might name it: error_lang.php Within the file you will assign each line of text to an array called -$lang with this prototype:: +``$lang`` with this prototype:: - $lang['language_key'] = "The actual message to be shown"; + $lang['language_key'] = 'The actual message to be shown'; .. note:: It's a good practice to use a common prefix for all messages in a given file to avoid collisions with similarly named items in other @@ -39,9 +38,9 @@ $lang with this prototype:: :: - $lang['error_email_missing'] = "You must submit an email address"; - $lang['error_url_missing'] = "You must submit a URL"; - $lang['error_username_missing'] = "You must submit a username"; + $lang['error_email_missing'] = 'You must submit an email address'; + $lang['error_url_missing'] = 'You must submit a URL'; + $lang['error_username_missing'] = 'You must submit a username'; Loading A Language File ======================= @@ -54,7 +53,9 @@ first. Loading a language file is done with the following code:: Where filename is the name of the file you wish to load (without the file extension), and language is the language set containing it (ie, english). If the second parameter is missing, the default language set -in your application/config/config.php file will be used. +in your **application/config/config.php** file will be used. + +.. note:: The *language* parameter can only consist of letters. Fetching a Line of Text ======================= @@ -64,27 +65,28 @@ text using this function:: $this->lang->line('language_key'); -Where language_key is the array key corresponding to the line you wish +Where *language_key* is the array key corresponding to the line you wish to show. -Note: This function simply returns the line. It does not echo it for -you. +You can optionally pass FALSE as the second argument of that method to +disable error logging, in case you're not sure if the line exists:: + + $this->lang->line('misc_key', FALSE); + +.. note:: This method simply returns the line. It does not echo it. Using language lines as form labels ----------------------------------- This feature has been deprecated from the language library and moved to -the lang() function of the :doc:`Language -helper <../helpers/language_helper>`. +the :php:func:`lang()` function of the :doc:`Language Helper +<../helpers/language_helper>`. Auto-loading Languages ====================== If you find that you need a particular language globally throughout your -application, you can tell CodeIgniter to -:doc:`auto-load <../general/autoloader>` it during system -initialization. This is done by opening the -application/config/autoload.php file and adding the language(s) to the -autoload array. - - +application, you can tell CodeIgniter to :doc:`auto-load +<../general/autoloader>` it during system initialization. This is done +by opening the **application/config/autoload.php** file and adding the +language(s) to the autoload array.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/loader.rst b/user_guide_src/source/libraries/loader.rst index aadf9740a..615aba1c2 100644 --- a/user_guide_src/source/libraries/loader.rst +++ b/user_guide_src/source/libraries/loader.rst @@ -4,6 +4,7 @@ Loader Class Loader, as the name suggests, is used to load elements. These elements can be libraries (classes) :doc:`View files <../general/views>`, +:doc:`Drivers <../general/drivers>`, :doc:`Helpers <../general/helpers>`, :doc:`Models <../general/models>`, or your own files. @@ -74,6 +75,70 @@ Assigning a Library to a different object name If the third (optional) parameter is blank, the library will usually be assigned to an object with the same name as the library. For example, if +the library is named Calendar, it will be assigned to a variable named +$this->calendar. + +If you prefer to set your own class names you can pass its value to the +third parameter:: + + $this->load->library('calendar', '', 'my_calendar'); + + // Calendar class is now accessed using: + + $this->my_calendar + +Please take note, when multiple libraries are supplied in an array for +the first parameter, this parameter is discarded. + +$this->load->driver('parent_name', $config, 'object name') +=========================================================== + +This function is used to load driver libraries. Where parent_name is the +name of the parent class you want to load. + +As an example, if you would like to use sessions with CodeIgniter, the first +step is to load the session driver within your controller:: + + $this->load->driver('session'); + +Once loaded, the library will be ready for use, using +$this->session->*some_function*(). + +Driver files must be stored in a subdirectory within the main +"libraries" folder, or within your personal application/libraries +folder. The subdirectory must match the parent class name. Read the +:doc:`Drivers <../general/drivers>` description for details. + +Additionally, multiple driver libraries can be loaded at the same time by +passing an array of drivers to the load function. + +:: + + $this->load->driver(array('session', 'cache')); + +Setting options +--------------- + +The second (optional) parameter allows you to optionally pass +configuration settings. You will typically pass these as an array:: + + $config = array ( + 'sess_driver' => 'cookie', + 'sess_encrypt_cookie' => true, + 'encryption_key' => 'mysecretkey' + ); + + $this->load->driver('session', $config); + +Config options can usually also be set via a config file. Each library +is explained in detail in its own page, so please read the information +regarding each one you would like to use. + +Assigning a Driver to a different object name +---------------------------------------------- + +If the third (optional) parameter is blank, the library will be assigned +to an object with the same name as the parent class. For example, if the library is named Session, it will be assigned to a variable named $this->session. @@ -86,8 +151,8 @@ third parameter:: $this->my_session -Please take note, when multiple libraries are supplied in an array for -the first parameter, this parameter is discarded. +.. note:: Driver libraries may also be loaded with the library() method, + but it is faster to use driver() $this->load->view('file_name', $data, true/false) ================================================== @@ -279,6 +344,6 @@ calling add_package_path(). $this->load->remove_package_path(APPPATH.'my_app'); // Again without the second parameter: - $this->load->add_package_path(APPPATH.'my_app', TRUE); + $this->load->add_package_path(APPPATH.'my_app'); $this->load->view('my_app_index'); // Loads - $this->load->view('welcome_message'); // Loads
\ No newline at end of file + $this->load->view('welcome_message'); // Loads diff --git a/user_guide_src/source/libraries/migration.rst b/user_guide_src/source/libraries/migration.rst index 5192f1f29..1a73fb78d 100644 --- a/user_guide_src/source/libraries/migration.rst +++ b/user_guide_src/source/libraries/migration.rst @@ -2,4 +2,162 @@ Migrations Class ################ -Coming soon.
\ No newline at end of file +Migrations are a convenient way for you to alter your database in a +structured and organized manner. You could edit fragments of SQL by hand +but you would then be responsible for telling other developers that they +need to go and run them. You would also have to keep track of which changes +need to be run against the production machines next time you deploy. + +The database table **migration** tracks which migrations have already been +run so all you have to do is update your application files and +call **$this->migrate->current()** to work out which migrations should be run. +The current version is found in **config/migration.php**. + +******************** +Migration file names +******************** + +Each Migration is run in numeric order forward or backwards depending on the +method taken. Two numbering styles are available: + +* **Sequential:** each migration is numbered in sequence, starting with **001**. + Each number must be three digits, and there must not be any gaps in the + sequence. (This was the numbering scheme prior to CodeIgniter 3.0.) +* **Timestamp:** each migration is numbered using the timestamp when the migration + was created, in **YYYYMMDDHHIISS** format (e.g. **20121031100537**). This + helps prevent numbering conflicts when working in a team environment, and is + the preferred scheme in CodeIgniter 3.0 and later. + +The desired style may be selected using the **$config['migration_type']** +setting in your **migration.php** config file. + +Regardless of which numbering style you choose to use, prefix your migration +files with the migration number followed by an underscore and a descriptive +name for the migration. For example: + +* **001_add_blog.php** (sequential numbering) +* **20121031100537_add_blog.php** (timestamp numbering) + +****************** +Create a Migration +****************** + +This will be the first migration for a new site which has a blog. All +migrations go in the folder **application/migrations/** and have names such +as **20121031100537_add_blog.php**.:: + + <?php + + defined('BASEPATH') OR exit('No direct script access allowed'); + + class Migration_Add_blog extends CI_Migration { + + public function up() + { + $this->dbforge->add_field(array( + 'blog_id' => array( + 'type' => 'INT', + 'constraint' => 5, + 'unsigned' => TRUE, + 'auto_increment' => TRUE + ), + 'blog_title' => array( + 'type' => 'VARCHAR', + 'constraint' => '100', + ), + 'blog_description' => array( + 'type' => 'TEXT', + 'null' => TRUE, + ), + )); + $this->dbforge->add_key('blog_id', TRUE); + $this->dbforge->create_table('blog'); + } + + public function down() + { + $this->dbforge->drop_table('blog'); + } + } + +Then in **application/config/migration.php** set **$config['migration_version'] = 1;**. + +************* +Usage Example +************* + +In this example some simple code is placed in **application/controllers/migrate.php** +to update the schema.:: + + <?php + + class Migrate extends CI_Controller + { + public function index() + { + $this->load->library('migration'); + + if ($this->migration->current() === FALSE) + { + show_error($this->migration->error_string()); + } + } + } + +****************** +Function Reference +****************** + +$this->migration->current() +============================ + +The current migration is whatever is set for **$config['migration_version']** in +**application/config/migration.php**. + +$this->migration->error_string() +================================= + +This returns a string of errors while performing a migration. + +$this->migration->find_migrations() +==================================== + +An array of migration filenames are returned that are found in the **migration_path** +property. + +$this->migration->latest() +=========================== + +This works much the same way as current() but instead of looking for +the **$config['migration_version']** the Migration class will use the very +newest migration found in the filesystem. + +$this->migration->version() +============================ + +Version can be used to roll back changes or step forwards programmatically to +specific versions. It works just like current but ignores **$config['migration_version']**.:: + + $this->load->library('migration'); + + $this->migration->version(5); + +********************* +Migration Preferences +********************* + +The following is a table of all the config options for migrations. + +========================== ====================== ========================== ============================================= +Preference Default Options Description +========================== ====================== ========================== ============================================= +**migration_enabled** FALSE TRUE / FALSE Enable or disable migrations. +**migration_path** APPPATH.'migrations/' None The path to your migrations folder. +**migration_version** 0 None The current version your database should use. +**migration_table** migrations None The table name for storing the schema + version number. +**migration_auto_latest** FALSE TRUE / FALSE Enable or disable automatically + running migrations. +**migration_type** 'timestamp' 'timestamp' / 'sequential' The type of numeric identifier used to name + migration files. +========================== ====================== ========================== ============================================= diff --git a/user_guide_src/source/libraries/output.rst b/user_guide_src/source/libraries/output.rst index 0472d14cf..a3d67b847 100644 --- a/user_guide_src/source/libraries/output.rst +++ b/user_guide_src/source/libraries/output.rst @@ -53,17 +53,37 @@ You can also set the character set of the document, by passing a second argument $this->output->set_content_type('css', 'utf-8'); -$this->output->get_content_type(); -========================================== +$this->output->get_content_type() +================================= -Returns the Content-Type HTTP header that's currently in use. +Returns the Content-Type HTTP header that's currently in use, +excluding the character set value. $mime = $this->output->get_content_type(); .. note:: If not set, the default return value is 'text/html'. -$this->output->get_output(); -============================= +$this->output->get_header() +=========================== + +Gets the requested HTTP header value, if set. + +If the header is not set, NULL will be returned. +If an empty value is passed to the method, it will return FALSE. + +Example:: + + $this->output->set_content_type('text/plain', 'UTF-8'); + echo $this->output->get_header('content-type'); + // Outputs: text/plain; charset=utf-8 + +.. note:: The header name is compared in a case-insensitive manner. + +.. note:: Raw headers sent via PHP's native ``header()`` function are + also detected. + +$this->output->get_output() +=========================== Permits you to manually retrieve any output that has been sent for storage in the output class. Usage example:: @@ -105,6 +125,9 @@ Permits you to manually set a server status header. Example:: `See here <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>`_ for a full list of headers. +.. note:: This method is an alias for :doc:`Common function <../general/common_functions>` + ``set_status_header()``. + $this->output->enable_profiler(); ================================== diff --git a/user_guide_src/source/libraries/pagination.rst b/user_guide_src/source/libraries/pagination.rst index 7d750bd23..d9d3f5092 100644 --- a/user_guide_src/source/libraries/pagination.rst +++ b/user_guide_src/source/libraries/pagination.rst @@ -80,8 +80,8 @@ The number of "digit" links you would like before and after the selected page number. For example, the number 2 will place two digits on either side, as in the example links at the very top of this page. -$config['use_page_number'] = TRUE; -================================== +$config['use_page_numbers'] = TRUE; +=================================== By default, the URI segment will use the starting index for the items you are paginating. If you prefer to show the the actual page number, diff --git a/user_guide_src/source/libraries/security.rst b/user_guide_src/source/libraries/security.rst index e7d25555f..05553142f 100644 --- a/user_guide_src/source/libraries/security.rst +++ b/user_guide_src/source/libraries/security.rst @@ -26,7 +26,7 @@ processing since it requires a fair amount of processing overhead. To filter data through the XSS filter use this function: $this->security->xss_clean() -============================= +============================ Here is an usage example:: @@ -56,7 +56,7 @@ browser may attempt to execute. } $this->security->sanitize_filename() -===================================== +==================================== When accepting filenames from user input, it is best to sanitize them to prevent directory traversal and other security related issues. To do so, @@ -76,16 +76,35 @@ parameter, $relative_path to TRUE. Cross-site request forgery (CSRF) ================================= -You can enable csrf protection by opening your +You can enable CSRF protection by opening your application/config/config.php file and setting this:: $config['csrf_protection'] = TRUE; -If you use the :doc:`form helper <../helpers/form_helper>` the -form_open() function will automatically insert a hidden csrf field in -your forms. +If you use the :doc:`form helper <../helpers/form_helper>`, then +``form_open()`` will automatically insert a hidden csrf field in +your forms. If not, then you can use ``csrf_get_token_name()`` +and ``csrf_get_hash()`` -Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter:: +:: + + $csrf = array( + 'name' => $this->security->csrf_get_token_name(), + 'hash' => $this->security->csrf_get_hash() + ); + + ... + + <input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" /> + +Tokens may be either regenerated on every submission (default) or +kept the same throughout the life of the CSRF cookie. The default +regeneration of tokens provides stricter security, but may result +in usability concerns as other tokens become invalid (back/forward +navigation, multiple tabs/windows, asynchronous actions, etc). You +may alter this behavior by editing the following config parameter + +:: $config['csrf_regeneration'] = TRUE; @@ -95,3 +114,15 @@ by editing the 'csrf_exclude_uris' config parameter:: $config['csrf_exclude_uris'] = array('api/person/add'); +$this->security->get_csrf_token_name() +====================================== + +Returns the CSRF token name, which is set by +``$config['csrf_token_name']``. + +$this->security->get_csrf_hash() +================================ + +Returns the CSRF hash value. Useful in combination with +``get_csrf_token_name()`` for manually building forms or +sending valid AJAX POST requests.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/sessions.rst b/user_guide_src/source/libraries/sessions.rst index 5400524a9..36c7c1d32 100644 --- a/user_guide_src/source/libraries/sessions.rst +++ b/user_guide_src/source/libraries/sessions.rst @@ -1,29 +1,19 @@ -############# -Session Class -############# +############## +Session Driver +############## The Session class permits you maintain a user's "state" and track their -activity while they browse your site. The Session class stores session -information for each user as serialized (and optionally encrypted) data -in a cookie. It can also store the session data in a database table for -added security, as this permits the session ID in the user's cookie to -be matched against the stored session ID. By default only the cookie is -saved. If you choose to use the database option you'll need to create -the session table as indicated below. - -.. note:: The Session class does **not** utilize native PHP sessions. It - generates its own session data, offering more flexibility for - developers. - -.. note:: Even if you are not using encrypted sessions, you must set - an :doc:`encryption key <./encryption>` in your config file which is used - to aid in preventing session data manipulation. +activity while they browse your site. CodeIgniter offers two default +session drivers: the classic `Cookie Driver`_, and the `Native Driver`_, +which supports usage of the native PHP Session mechanism. In addition, +you may create your own `Custom Drivers`_ to store session data however +you wish, while still taking advantage of the features of the Session class. Initializing a Session ====================== Sessions will typically run globally with each page load, so the session -class must either be :doc:`initialized <../general/libraries>` in your +class must either be :doc:`initialized <../general/drivers>` in your :doc:`controller <../general/controllers>` constructors, or it can be :doc:`auto-loaded <../general/autoloader>` by the system. For the most part the session class will run unattended in the background, so simply @@ -31,9 +21,9 @@ initializing the class will cause it to read, create, and update sessions. To initialize the Session class manually in your controller constructor, -use the $this->load->library function:: +use the $this->load->driver function:: - $this->load->library('session'); + $this->load->driver('session'); Once loaded, the Sessions library object will be available using: $this->session @@ -42,11 +32,10 @@ How do Sessions work? ===================== When a page is loaded, the session class will check to see if valid -session data exists in the user's session cookie. If sessions data does -**not** exist (or if it has expired) a new session will be created and -saved in the cookie. If a session does exist, its information will be -updated and the cookie will be updated. With each update, the -session_id will be regenerated. +session data exists in the user's session. If sessions data does **not** +exist (or if it has expired) a new session will be created and saved. +If a session does exist, its information will be updated. With each update, +the session_id will be regenerated. It's important for you to understand that once initialized, the Session class runs automatically. There is nothing you need to do to cause the @@ -79,19 +68,12 @@ prototype:: 'last_activity' => timestamp ) -If you have the encryption option enabled, the serialized array will be -encrypted before being stored in the cookie, making the data highly -secure and impervious to being read or altered by someone. More info -regarding encryption can be :doc:`found here <encryption>`, although -the Session class will take care of initializing and encrypting the data -automatically. - -Note: Session cookies are only updated every five minutes by default to -reduce processor load. If you repeatedly reload a page you'll notice -that the "last activity" time only updates if five minutes or more has -passed since the last time the cookie was written. This time is -configurable by changing the $config['sess_time_to_update'] line in -your system/config/config.php file. +.. note:: Sessions are only updated every five minutes by default to + reduce processor load. If you repeatedly reload a page you'll notice + that the "last activity" time only updates if five minutes or more has + passed since the last time the cookie was written. This time is + configurable by changing the $config['sess_time_to_update'] line in + your system/config/config.php file. Retrieving Session Data ======================= @@ -106,7 +88,7 @@ fetch. For example, to fetch the session ID you will do this:: $session_id = $this->session->userdata('session_id'); -.. note:: The function returns FALSE (boolean) if the item you are +.. note:: The function returns NULL if the item you are trying to access does not exist. Adding Custom Session Data @@ -117,7 +99,7 @@ to it and it will be stored in the user's cookie. Why would you want to do this? Here's one example: Let's say a particular user logs into your site. Once authenticated, you -could add their username and email address to the session cookie, making +could add their username and email address to the session, making that data globally available to you without having to run a database query when you need it. @@ -144,11 +126,11 @@ supports this syntax. $this->session->set_userdata('some_name', 'some_value'); +If you want to verify that a userdata value exists, call has_userdata(). -.. note:: Cookies can only hold 4KB of data, so be careful not to exceed - the capacity. The encryption process in particular produces a longer - data string than the original so keep careful track of how much data you - are storing. +:: + + $this->session->has_userdata('some_name'); Retrieving All Session Data =========================== @@ -195,8 +177,8 @@ available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted"). -Note: Flash variables are prefaced with "flash\_" so avoid this prefix -in your own session names. +.. note:: Flash variables are prefaced with "flash\_" so avoid this prefix + in your own session names. To add flashdata:: @@ -209,7 +191,7 @@ set_userdata(). To read a flashdata variable:: $this->session->flashdata('item'); - + An array of all flashdata can be retrieved as follows:: $this->session->all_flashdata(); @@ -217,14 +199,169 @@ An array of all flashdata can be retrieved as follows:: If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() function. +You can either pass a single item or an array of flashdata items to keep. :: $this->session->keep_flashdata('item'); + $this->session->keep_flashdata(array('item1', 'item2', 'item3')); + +Tempdata +======== + +CodeIgniter also supports "tempdata", or session data with a specific +expiration time. After the value expires, or the session expires or is +deleted, the value is automatically removed. + +To add tempdata:: + + $expire = 300; // Expire in 5 minutes + + $this->session->set_tempdata('item', 'value', $expire); + +You can also pass an array to set_tempdata():: + + $tempdata = array('newuser' => TRUE, 'message' => 'Thanks for joining!'); + + $this->session->set_tempdata($tempdata, '', $expire); + +.. note:: If the expiration is omitted or set to 0, the default expiration of + 5 minutes will be used. + +To read a tempdata variable:: + + $this->session->tempdata('item'); + +If you need to remove a tempdata value before it expires, +use unset_tempdata():: + + $this->session->unset_tempdata('item'); + +Destroying a Session +==================== + +To clear the current session:: + + $this->session->sess_destroy(); + +.. note:: This function should be the last one called, and even flash + variables will no longer be available. If you only want some items + destroyed and not all, use unset_userdata(). + +Session Preferences +=================== + +You'll find the following Session related preferences in your +application/config/config.php file: + +=========================== =============== =========================== ========================================================================== +Preference Default Options Description +=========================== =============== =========================== ========================================================================== +**sess_driver** cookie cookie/native/*custom* The initial session driver to load. +**sess_valid_drivers** cookie, native None Additional valid drivers which may be loaded. +**sess_cookie_name** ci_session None The name you want the session cookie saved as (data for Cookie driver or + session ID for Native driver). +**sess_expiration** 7200 None The number of seconds you would like the session to last. The default + value is 2 hours (7200 seconds). If you would like a non-expiring + session set the value to zero: 0 +**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser + window is closed. +**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data (Cookie driver only). +**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the + table before enabling this option (Cookie driver only). +**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table (Cookie driver only). +**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself + and create a new session id. +**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data. + Note that some ISPs dynamically changes the IP, so if you want a + non-expiring session you will likely set this to FALSE. +**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data. +=========================== =============== =========================== ========================================================================== + +In addition to the values above, the cookie and native drivers apply the +following configuration values shared by the :doc:`Input <input>` and +:doc:`Security <security>` classes: + +=========================== =============== ========================================================================== +Preference Default Description +=========================== =============== ========================================================================== +**cookie_prefix** '' Set a cookie name prefix in order to avoid name collisions +**cookie_domain** '' The domain for which the session is applicable +**cookie_path** / The path to which the session is applicable +=========================== =============== ========================================================================== + +Session Drivers +=============== +By default, the `Cookie Driver`_ is loaded when a session is initialized. +However, any valid driver may be selected with the $config['sess_driver'] +line in your config.php file. + +The session driver library comes with the cookie and native drivers +installed, and `Custom Drivers`_ may also be installed by the user. + +Typically, only one driver will be used at a time, but CodeIgniter does +support loading multiple drivers. If a specific valid driver is called, it +will be automatically loaded. Or, an additional driver may be explicitly +loaded by calling load_driver():: + + $this->session->load_driver('native'); + +The Session library keeps track of the most recently selected driver to call +for driver methods. Normally, session class methods are called directly on +the parent class, as illustrated above. However, any methods called through +a specific driver will select that driver before invoking the parent method. + +So, alternation between multiple drivers can be achieved by specifying which +driver to use for each call:: + + $this->session->native->set_userdata('foo', 'bar'); + + $this->session->cookie->userdata('foo'); + + $this->session->native->unset_userdata('foo'); + +Notice in the previous example that the *native* userdata value 'foo' +would be set to 'bar', which would NOT be returned by the call for +the *cookie* userdata 'foo', nor would the *cookie* value be unset by +the call to unset the *native* 'foo' value. The drivers maintain independent +sets of values, regardless of key names. + +A specific driver may also be explicitly selected for use by pursuant +methods with the select_driver() call:: + + $this->session->select_driver('native'); + + $this->session->userdata('item'); // Uses the native driver + +Cookie Driver +------------- + +The Cookie driver stores session information for each user as serialized +(and optionally encrypted) data in a cookie. It can also store the session +data in a database table for added security, as this permits the session ID +in the user's cookie to be matched against the stored session ID. By default +only the cookie is saved. If you choose to use the database option you'll +need to create the session table as indicated below. + +If you have the encryption option enabled, the serialized array will be +encrypted before being stored in the cookie, making the data highly +secure and impervious to being read or altered by someone. More info +regarding encryption can be :doc:`found here <encryption>`, although +the Session class will take care of initializing and encrypting the data +automatically. + +.. note:: Even if you are not using encrypted sessions, you must set + an :doc:`encryption key <./encryption>` in your config file which is used + to aid in preventing session data manipulation. + +.. note:: Cookies can only hold 4KB of data, so be careful not to exceed + the capacity. The encryption process in particular produces a longer + data string than the original so keep careful track of how much data you + are storing. Saving Session Data to a Database -================================= +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ While the session data array stored in the user's cookie contains a Session ID, unless you store session data in a database there is no way @@ -249,7 +386,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`) ); @@ -267,44 +404,82 @@ session class:: $config['sess_table_name'] = 'ci_sessions'; -.. note:: The Session class has built-in garbage collection which clears +.. note:: The Cookie driver has built-in garbage collection which clears out expired sessions so you do not need to write your own routine to do it. -Destroying a Session -==================== +Native Driver +------------- -To clear the current session:: +The Native driver relies on native PHP sessions to store data in the +$_SESSION superglobal array. All stored values continue to be available +through $_SESSION, but flash- and temp- data items carry special prefixes. - $this->session->sess_destroy(); +Custom Drivers +-------------- -.. note:: This function should be the last one called, and even flash - variables will no longer be available. If you only want some items - destroyed and not all, use unset_userdata(). +You may also :doc:`create your own <../general/creating_drivers>` custom +session drivers. A session driver basically manages an array of name/value +pairs with some sort of storage mechanism. -Session Preferences -=================== +To make a new driver, extend CI_Session_driver. Overload the initialize() +method and read or create session data. Then implement a save handler to +write changed data to storage (sess_save), a destroy handler to remove +deleted data (sess_destroy), a regenerate handler to make a new session ID +(sess_regenerate), and an access handler to expose the data (get_userdata). +Your initial class might look like:: -You'll find the following Session related preferences in your -application/config/config.php file: + class CI_Session_custom extends CI_Session_driver { + protected function initialize() + { + // Read existing session data or create a new one + } -=========================== =============== =========================== ========================================================================== -Preference Default Options Description -=========================== =============== =========================== ========================================================================== -**sess_cookie_name** ci_session None The name you want the session cookie saved as. -**sess_expiration** 7200 None The number of seconds you would like the session to last. The default - value is 2 hours (7200 seconds). If you would like a non-expiring - session set the value to zero: 0 -**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser - window is closed. -**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data. -**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the - table before enabling this option. -**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table. -**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself - and create a new session id. -**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data. - Note that some ISPs dynamically changes the IP, so if you want a - non-expiring session you will likely set this to FALSE. -**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data. -=========================== =============== =========================== ==========================================================================
\ No newline at end of file + public function sess_save() + { + // Save current data to storage + } + + public function sess_destroy() + { + // Destroy the current session and clean up storage + } + + public function sess_regenerate() + { + // Create new session ID + } + + public function &get_userdata() + { + // Return a reference to your userdata array + } + } + +Notice that get_userdata() returns a reference so the parent library is +accessing the same array the driver object is using. This saves memory +and avoids synchronization issues during usage. + +Put your driver in the libraries/Session/drivers folder anywhere in your +package paths. This includes the application directory, the system directory, +or any path you add with $CI->load->add_package_path(). Your driver must be +named CI_Session_<name>, and your filename must be Session_<name>.php, +preferably also capitalized, such as:: + + CI_Session_foo in libraries/Session/drivers/Session_foo.php + +Then specify the driver by setting 'sess_driver' in your config.php file or as a +parameter when loading the CI_Session object:: + + $config['sess_driver'] = 'foo'; + +OR:: + + $CI->load->driver('session', array('sess_driver' => 'foo')); + +The driver specified by 'sess_driver' is automatically included as a valid +driver. However, if you want to make a custom driver available as an option +without making it the initially loaded driver, set 'sess_valid_drivers' in +your config.php file to an array including your driver name:: + + $config['sess_valid_drivers'] = array('sess_driver'); diff --git a/user_guide_src/source/libraries/trackback.rst b/user_guide_src/source/libraries/trackback.rst index 07b2b2177..f9e0df882 100644 --- a/user_guide_src/source/libraries/trackback.rst +++ b/user_guide_src/source/libraries/trackback.rst @@ -114,7 +114,7 @@ store them. Here is a basic prototype for such a table:: excerpt text NOT NULL, blog_name varchar(100) NOT NULL, tb_date int(10) NOT NULL, - ip_address varchar(16) NOT NULL, + ip_address varchar(45) NOT NULL, PRIMARY KEY `tb_id` (`tb_id`), KEY `entry_id` (`entry_id`) ); diff --git a/user_guide_src/source/libraries/unit_testing.rst b/user_guide_src/source/libraries/unit_testing.rst index 03819b27c..6bd91bf88 100644 --- a/user_guide_src/source/libraries/unit_testing.rst +++ b/user_guide_src/source/libraries/unit_testing.rst @@ -131,7 +131,7 @@ default: - Any notes you entered for the test (notes) You can customize which of these items get displayed by using -$this->unit->set_items(). For example, if you only wanted the test name +$this->unit->set_test_items(). For example, if you only wanted the test name and the result displayed: Customizing displayed tests diff --git a/user_guide_src/source/libraries/user_agent.rst b/user_guide_src/source/libraries/user_agent.rst index 855ece29d..97abd2244 100644 --- a/user_guide_src/source/libraries/user_agent.rst +++ b/user_guide_src/source/libraries/user_agent.rst @@ -72,7 +72,7 @@ Returns TRUE/FALSE (boolean) if the user agent is a known web browser. { echo 'You are using Safari.'; } - else if ($this->agent->is_browser()) + elseif ($this->agent->is_browser()) { echo 'You are using a browser.'; } @@ -94,7 +94,7 @@ Returns TRUE/FALSE (boolean) if the user agent is a known mobile device. { $this->load->view('iphone/home'); } - else if ($this->agent->is_mobile()) + elseif ($this->agent->is_mobile()) { $this->load->view('mobile/home'); } diff --git a/user_guide_src/source/libraries/xmlrpc.rst b/user_guide_src/source/libraries/xmlrpc.rst index dfb88114e..b478a2ded 100644 --- a/user_guide_src/source/libraries/xmlrpc.rst +++ b/user_guide_src/source/libraries/xmlrpc.rst @@ -297,7 +297,7 @@ The Client ---------- Using a text editor, create a controller called xmlrpc_client.php. In -it, place this code and save it to your applications/controllers/ +it, place this code and save it to your application/controllers/ folder:: <?php @@ -338,7 +338,7 @@ The Server ---------- Using a text editor, create a controller called xmlrpc_server.php. In -it, place this code and save it to your applications/controllers/ +it, place this code and save it to your application/controllers/ folder:: <?php diff --git a/user_guide_src/source/overview/cheatsheets.rst b/user_guide_src/source/overview/cheatsheets.rst deleted file mode 100644 index 2e277aa9a..000000000 --- a/user_guide_src/source/overview/cheatsheets.rst +++ /dev/null @@ -1,16 +0,0 @@ -####################### -CodeIgniter Cheatsheets -####################### - -Library Reference -================= - -`|CodeIgniter Library -Reference| <../images/codeigniter_1.7.1_library_reference.pdf>`_ -Helpers Reference -================= - -`|image1| <../images/codeigniter_1.7.1_helper_reference.pdf>`_ - -.. |CodeIgniter Library Reference| image:: ../images/codeigniter_1.7.1_library_reference.png -.. |image1| image:: ../images/codeigniter_1.7.1_helper_reference.png diff --git a/user_guide_src/source/overview/index.rst b/user_guide_src/source/overview/index.rst index dc91f78c4..d48a0bbe4 100644 --- a/user_guide_src/source/overview/index.rst +++ b/user_guide_src/source/overview/index.rst @@ -9,7 +9,6 @@ The following pages describe the broad concepts behind CodeIgniter: Getting Started <getting_started> CodeIgniter at a Glance <at_a_glance> - CodeIgniter Cheatsheets <cheatsheets> Supported Features <features> Application Flow Chart <appflow> Model-View-Controller <mvc> diff --git a/user_guide_src/source/tutorial/news_section.rst b/user_guide_src/source/tutorial/news_section.rst index 82b3e3b38..b64ea2aae 100644 --- a/user_guide_src/source/tutorial/news_section.rst +++ b/user_guide_src/source/tutorial/news_section.rst @@ -22,19 +22,19 @@ your database properly as described :: - <?php - class News_model extends CI_Model { + <?php + class News_model extends CI_Model { - public function __construct() - { - $this->load->database(); - } - } + public function __construct() + { + $this->load->database(); + } + } This code looks similar to the controller code that was used earlier. It -creates a new model by extending CI\_Model and loads the database +creates a new model by extending ``CI_Model`` and loads the database library. This will make the database class available through the -$this->db object. +``$this->db`` object. Before querying the database, a database schema has to be created. Connect to your database and run the SQL command below. Also add some @@ -42,14 +42,14 @@ seed records. :: - CREATE TABLE news ( - id int(11) NOT NULL AUTO_INCREMENT, - title varchar(128) NOT NULL, - slug varchar(128) NOT NULL, - text text NOT NULL, - PRIMARY KEY (id), - KEY slug (slug) - ); + CREATE TABLE news ( + id int(11) NOT NULL AUTO_INCREMENT, + title varchar(128) NOT NULL, + slug varchar(128) NOT NULL, + text text NOT NULL, + PRIMARY KEY (id), + KEY slug (slug) + ); Now that the database and a model have been set up, you'll need a method to get all of our posts from our database. To do this, the database @@ -61,22 +61,22 @@ following code to your model. :: - public function get_news($slug = FALSE) - { - if ($slug === FALSE) - { - $query = $this->db->get('news'); - return $query->result_array(); - } + public function get_news($slug = FALSE) + { + if ($slug === FALSE) + { + $query = $this->db->get('news'); + return $query->result_array(); + } - $query = $this->db->get_where('news', array('slug' => $slug)); - return $query->row_array(); - } + $query = $this->db->get_where('news', array('slug' => $slug)); + return $query->row_array(); + } With this code you can perform two different queries. You can get all news records, or get a news item by its `slug <#>`_. You might have noticed that the $slug variable wasn't sanitized before running the -query; Query Builder does this for you. +query; :doc:`Query Builder <../database/query_builder>` does this for you. Display the news ---------------- @@ -89,30 +89,30 @@ application/controllers/news.php. :: - <?php - class News extends CI_Controller { + <?php + class News extends CI_Controller { - public function __construct() - { - parent::__construct(); - $this->load->model('news_model'); - } + public function __construct() + { + parent::__construct(); + $this->load->model('news_model'); + } - public function index() - { - $data['news'] = $this->news_model->get_news(); - } + public function index() + { + $data['news'] = $this->news_model->get_news(); + } - public function view($slug) - { - $data['news'] = $this->news_model->get_news($slug); - } - } + public function view($slug = NULL) + { + $data['news_item'] = $this->news_model->get_news($slug); + } + } Looking at the code, you may see some similarity with the files we -created earlier. First, the "\_\_construct" method: it calls the -constructor of its parent class (CI\_Controller) and loads the model, so -it can be used in all other methods in this controller. +created earlier. First, the ``__construct()`` method: it calls the +constructor of its parent class (``CI_Controller``) and loads the model, +so it can be used in all other methods in this controller. Next, there are two methods to view all news items and one for a specific news item. You can see that the $slug variable is passed to the @@ -125,15 +125,15 @@ the views. :: - public function index() - { - $data['news'] = $this->news_model->get_news(); - $data['title'] = 'News archive'; + public function index() + { + data['news'] = $this->news_model->get_news(); + $data['title'] = 'News archive'; - $this->load->view('templates/header', $data); - $this->load->view('news/index', $data); - $this->load->view('templates/footer'); - } + $this->load->view('templates/header', $data); + $this->load->view('news/index', $data); + $this->load->view('templates/footer'); + } The code above gets all news records from the model and assigns it to a variable. The value for the title is also assigned to the $data['title'] @@ -143,20 +143,20 @@ and add the next piece of code. :: - <?php foreach ($news as $news_item): ?> + <?php foreach ($news as $news_item): ?> - <h2><?php echo $news_item['title'] ?></h2> - <div id="main"> - <?php echo $news_item['text'] ?> - </div> - <p><a href="<?php echo $news_item['slug'] ?>">View article</a></p> + <h2><?php echo $news_item['title'] ?></h2> + <div id="main"> + <?php echo $news_item['text'] ?> + </div> + <p><a href="<?php echo $news_item['slug'] ?>">View article</a></p> - <?php endforeach ?> + <?php endforeach ?> Here, each news item is looped and displayed to the user. You can see we wrote our template in PHP mixed with HTML. If you prefer to use a template language, you can use CodeIgniter's `Template -Parser <../libraries/parser.html>`_ class or a third party parser. +Parser <../libraries/parser>`_ class or a third party parser. The news overview page is now done, but a page to display individual news items is still absent. The model created earlier is made in such @@ -166,32 +166,32 @@ news controller and add the following lines to the file. :: - public function view($slug) - { - $data['news_item'] = $this->news_model->get_news($slug); + public function view($slug = NULL) + { + $data['news_item'] = $this->news_model->get_news($slug); - if (empty($data['news_item'])) - { - show_404(); - } + if (empty($data['news_item'])) + { + show_404(); + } - $data['title'] = $data['news_item']['title']; + $data['title'] = $data['news_item']['title']; - $this->load->view('templates/header', $data); - $this->load->view('news/view', $data); - $this->load->view('templates/footer'); - } + $this->load->view('templates/header', $data); + $this->load->view('news/view', $data); + $this->load->view('templates/footer'); + } -Instead of calling the get\_news() method without a parameter, the $slug -variable is passed, so it will return the specific news item. The only -things left to do is create the corresponding view at -application/views/news/view.php. Put the following code in this file. +Instead of calling the ``get_news()`` method without a parameter, the +``$slug`` variable is passed, so it will return the specific news item. +The only things left to do is create the corresponding view at +*application/views/news/view.php*. Put the following code in this file. :: - <?php - echo '<h2>'.$news_item['title'].'</h2>'; - echo $news_item['text']; + <?php + echo '<h2>'.$news_item['title'].'</h2>'; + echo $news_item['text']; Routing ------- @@ -205,10 +205,10 @@ a slug to the view method in the news controller. :: - $route['news/(:any)'] = 'news/view/$1'; - $route['news'] = 'news'; - $route['(:any)'] = 'pages/view/$1'; - $route['default_controller'] = 'pages/view'; + $route['news/(:any)'] = 'news/view/$1'; + $route['news'] = 'news'; + $route['(:any)'] = 'pages/view/$1'; + $route['default_controller'] = 'pages/view'; Point your browser to your document root, followed by index.php/news and -watch your news page. +watch your news page.
\ No newline at end of file |