diff options
Diffstat (limited to 'user_guide_src/source/general')
30 files changed, 0 insertions, 3879 deletions
diff --git a/user_guide_src/source/general/alternative_php.rst b/user_guide_src/source/general/alternative_php.rst deleted file mode 100644 index 418d2e6eb..000000000 --- a/user_guide_src/source/general/alternative_php.rst +++ /dev/null @@ -1,75 +0,0 @@ -################################### -Alternate PHP Syntax for View Files -################################### - -If you do not utilize CodeIgniter's :doc:`template -engine <../libraries/parser>`, you'll be using pure PHP in your -View files. To minimize the PHP code in these files, and to make it -easier to identify the code blocks it is recommended that you use PHPs -alternative syntax for control structures and short tag echo statements. -If you are not familiar with this syntax, it allows you to eliminate the -braces from your code, and eliminate "echo" statements. - -Automatic Short Tag Support -=========================== - -.. note:: If you find that the syntax described in this page does not - 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. - -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. - -Alternative Echos -================= - -Normally to echo, or print out a variable you would do this:: - - <?php echo $variable; ?> - -With the alternative syntax you can instead do it this way:: - - <?=$variable?> - -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``:: - - <ul> - - <?php foreach ($todo as $item): ?> - - <li><?=$item?></li> - - <?php endforeach; ?> - - </ul> - -Notice that there are no braces. Instead, the end brace is replaced with -``endforeach``. Each of the control structures listed above has a similar -closing syntax: ``endif``, ``endfor``, ``endforeach``, and ``endwhile`` - -Also notice that instead of using a semicolon after each structure -(except the last one), there is a colon. This is important! - -Here is another example, using ``if``/``elseif``/``else``. Notice the colons:: - - <?php if ($username === 'sally'): ?> - - <h3>Hi Sally</h3> - - <?php elseif ($username === 'joe'): ?> - - <h3>Hi Joe</h3> - - <?php else: ?> - - <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 deleted file mode 100644 index 4d6528aae..000000000 --- a/user_guide_src/source/general/ancillary_classes.rst +++ /dev/null @@ -1,80 +0,0 @@ -########################## -Creating Ancillary Classes -########################## - -In some cases you may want to develop classes that exist apart from your -controllers but have the ability to utilize all of CodeIgniter's -resources. This is easily possible as you'll see. - -get_instance() -============== - -.. php:function:: get_instance() - - :returns: Reference to your controller's instance - :rtype: 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. - -Normally, to call any of the available methods, CodeIgniter 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: - -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``:: - - $CI =& get_instance(); - - $CI->load->helper('url'); - $CI->load->library('session'); - $CI->config->item('base_url'); - // etc. - -If you'll be using ``get_instance()`` inside another 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. diff --git a/user_guide_src/source/general/autoloader.rst b/user_guide_src/source/general/autoloader.rst deleted file mode 100644 index 2f1223e28..000000000 --- a/user_guide_src/source/general/autoloader.rst +++ /dev/null @@ -1,27 +0,0 @@ -###################### -Auto-loading Resources -###################### - -CodeIgniter comes with an "Auto-load" feature that permits libraries, -helpers, and models to be initialized automatically every time the -system runs. If you need certain resources globally throughout your -application you should consider auto-loading them for convenience. - -The following items can be loaded automatically: - -- 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. - -.. note:: Do not include the file extension (.php) when adding items to - the autoload array. - -Additionally, if you want CodeIgniter to use a `Composer <https://getcomposer.org/>`_ -auto-loader, just set ``$config['composer_autoload']`` to ``TRUE`` or -a custom path in **application/config/config.php**.
\ No newline at end of file diff --git a/user_guide_src/source/general/caching.rst b/user_guide_src/source/general/caching.rst deleted file mode 100644 index f499f6e93..000000000 --- a/user_guide_src/source/general/caching.rst +++ /dev/null @@ -1,71 +0,0 @@ -################ -Web Page Caching -################ - -CodeIgniter lets you cache your pages in order to achieve maximum -performance. - -Although CodeIgniter is quite fast, the amount of dynamic information -you display in your pages will correlate directly to the server -resources, memory, and processing cycles utilized, which affect your -page load speeds. By caching your pages, since they are saved in their -fully rendered state, you can achieve performance that nears that of -static web pages. - -How Does Caching Work? -====================== - -Caching can be enabled on a per-page basis, and you can set the length -of time that a page should remain cached before being refreshed. When a -page is loaded for the first time, the cache file will be written to -your application/cache folder. On subsequent page loads the cache file -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. - -Enabling Caching -================ - -To enable caching, put the following tag in any of your controller -methods:: - - $this->output->cache($n); - -Where ``$n`` is the number of **minutes** you wish the page to remain -cached between refreshes. - -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>`. - -.. important:: If you change configuration options that might affect - your output, you have to manually delete your cache files. - -.. note:: Before the cache files can be written you must set the file - 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 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 deleted file mode 100644 index 764a6b835..000000000 --- a/user_guide_src/source/general/cli.rst +++ /dev/null @@ -1,78 +0,0 @@ -################### -Running via the CLI -################### - -As well as calling an applications :doc:`Controllers <./controllers>` -via the URL in a browser they can also be loaded via the command-line -interface (CLI). - -.. contents:: Page Contents - -What is the CLI? -================ - -The command-line interface is a text-based method of interacting with -computers. For more information, check the `Wikipedia -article <http://en.wikipedia.org/wiki/Command-line_interface>`_. - -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* -- Make your cron-jobs inaccessible from being loaded in the URL by - checking the return value of :php:func:`is_cli()`. -- Make interactive "tasks" that can do things like set permissions, - prune cache folders, run backups, etc. -- Integrate with other applications in other languages. For example, a - random C++ script could call one command and run code in your models! - -Let's try it: Hello World! -========================== - -Let's create a simple controller so you can see it in action. Using your -text editor, create a file called Tools.php, and put the following code -in it:: - - <?php - class Tools extends CI_Controller { - - public function message($to = 'World') - { - echo "Hello {$to}!".PHP_EOL; - } - } - -Then save the file to your *application/controllers/* folder. - -Now normally you would visit the site using a URL similar to this:: - - example.com/index.php/tools/message/to - -Instead, we are going to open the terminal in Mac/Linux or go to Run > "cmd" -in Windows and navigate to our CodeIgniter project. - -.. code-block:: bash - - $ cd /path/to/project; - $ php index.php tools message - -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! - -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. diff --git a/user_guide_src/source/general/common_functions.rst b/user_guide_src/source/general/common_functions.rst deleted file mode 100644 index 3e3e42264..000000000 --- a/user_guide_src/source/general/common_functions.rst +++ /dev/null @@ -1,188 +0,0 @@ -################ -Common Functions -################ - -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. - -.. contents:: - :local: - -.. raw:: html - - <div class="custom-index container"></div> - -.. php:function:: is_php($version) - - :param string $version: Version number - :returns: TRUE if the running PHP version is at least the one specified or FALSE if not - :rtype: bool - - Determines if the PHP version being used is greater than the - supplied version number. - - Example:: - - if (is_php('5.3')) - { - $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. - -.. php:function:: is_really_writable($file) - - :param string $file: File path - :returns: TRUE if the path is writable, FALSE if not - :rtype: bool - - ``is_writable()`` returns TRUE on Windows servers when you really can't - write to the file as the OS reports to PHP as FALSE only if the - read-only attribute is marked. - - This function determines if a file is actually writable by attempting - to write to it first. Generally only recommended on platforms where - this information may be unreliable. - - Example:: - - if (is_really_writable('file.txt')) - { - echo "I could write to this if I wanted to"; - } - else - { - echo "File is not writable"; - } - - .. note:: See also `PHP bug #54709 <https://bugs.php.net/bug.php?id=54709>`_ for more info. - -.. php:function:: config_item($key) - - :param string $key: Config item key - :returns: Configuration key value or NULL if not found - :rtype: 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. - -.. :noindex: 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 - :rtype: void - - This function calls ``CI_Exception::show_error()``. For more info, - please see the :doc:`Error Handling <errors>` documentation. - -.. :noindex: function:: show_404([$page = ''[, $log_error = TRUE]]) - - :param string $page: URI string - :param bool $log_error: Whether to log the error - :rtype: void - - This function calls ``CI_Exception::show_404()``. For more info, - please see the :doc:`Error Handling <errors>` documentation. - -.. :noindex: function:: log_message($level, $message) - - :param string $level: Log level: 'error', 'debug' or 'info' - :param string $message: Message to log - :rtype: void - - This function is an alias for ``CI_Log::write_log()``. For more info, - please see the :doc:`Error Handling <errors>` documentation. - -.. php:function:: set_status_header($code[, $text = '']) - - :param int $code: HTTP Response status code - :param string $text: A custom message to set with the status code - :rtype: void - - Permits you to manually set a server status header. Example:: - - set_status_header(401); - // Sets the header as: Unauthorized - - `See here <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>`_ for - a full list of headers. - -.. 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: Sanitized string - :rtype: string - - This function prevents inserting NULL characters between ASCII - characters, like Java\\0script. - - Example:: - - remove_invisible_characters('Java\\0script'); - // Returns: 'Javascript' - -.. php:function:: html_escape($var) - - :param mixed $var: Variable to escape (string or array) - :returns: HTML escaped string(s) - :rtype: 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). - -.. php:function:: get_mimes() - - :returns: An associative array of file types - :rtype: array - - This function returns a *reference* to the MIMEs array from - *application/config/mimes.php*. - -.. php:function:: is_https() - - :returns: TRUE if currently using HTTP-over-SSL, FALSE if not - :rtype: bool - - Returns TRUE if a secure (HTTPS) connection is used and FALSE - in any other case (including non-HTTP requests). - -.. php:function:: is_cli() - - :returns: TRUE if currently running under CLI, FALSE otherwise - :rtype: bool - - Returns TRUE if the application is run through the command line - and FALSE if not. - - .. note:: This function checks both if the ``PHP_SAPI`` value is 'cli' - or if the ``STDIN`` constant is defined. - -.. php:function:: function_usable($function_name) - - :param string $function_name: Function name - :returns: TRUE if the function can be used, FALSE if not - :rtype: 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. - - .. note:: This function was introduced because Suhosin terminated - script execution, but this turned out to be a bug. A fix - has been available for some time (version 0.9.34), but is - unfortunately not released yet.
\ No newline at end of file diff --git a/user_guide_src/source/general/compatibility_functions.rst b/user_guide_src/source/general/compatibility_functions.rst deleted file mode 100644 index 584968663..000000000 --- a/user_guide_src/source/general/compatibility_functions.rst +++ /dev/null @@ -1,232 +0,0 @@ -####################### -Compatibility Functions -####################### - -CodeIgniter provides a set of compatibility functions that enable -you to use functions what are otherwise natively available in PHP, -but only in higher versions or depending on a certain extension. - -Being custom implementations, these functions will also have some -set of dependencies on their own, but are still useful if your -PHP setup doesn't offer them natively. - -.. note:: Much like the :doc:`common functions <common_functions>`, the - compatibility functions are always available, as long as - their dependencies are met. - -.. contents:: - :local: - -.. raw:: html - - <div class="custom-index container"></div> - -**************** -Password Hashing -**************** - -This set of compatibility functions offers a "backport" of PHP's -standard `Password Hashing extension <http://php.net/password>`_ -that is otherwise available only since PHP 5.5. - -Dependencies -============ - -- PHP 5.3.7 -- ``CRYPT_BLOWFISH`` support for ``crypt()`` - -Constants -========= - -- ``PASSWORD_BCRYPT`` -- ``PASSWORD_DEFAULT`` - -Function reference -================== - -.. php:function:: password_get_info($hash) - - :param string $hash: Password hash - :returns: Information about the hashed password - :rtype: array - - For more information, please refer to the `PHP manual for - password_get_info() <http://php.net/password_get_info>`_. - -.. php:function:: password_hash($password, $algo[, $options = array()]) - - :param string $password: Plain-text password - :param int $algo: Hashing algorithm - :param array $options: Hashing options - :returns: Hashed password or FALSE on failure - :rtype: string - - For more information, please refer to the `PHP manual for - password_hash() <http://php.net/password_hash>`_. - - .. note:: Unless you provide your own (and valid) salt, this function - has a further dependency on an available CSPRNG source. Each - of the following would satisfy that: - - ``mcrypt_create_iv()`` with ``MCRYPT_DEV_URANDOM`` - - ``openssl_random_pseudo_bytes()`` - - /dev/arandom - - /dev/urandom - -.. php:function:: password_needs_rehash() - - :param string $hash: Password hash - :param int $algo: Hashing algorithm - :param array $options: Hashing options - :returns: TRUE if the hash should be rehashed to match the given algorithm and options, FALSE otherwise - :rtype: bool - - For more information, please refer to the `PHP manual for - password_needs_rehash() <http://php.net/password_needs_rehash>`_. - -.. php:function:: password_verify($password, $hash) - - :param string $password: Plain-text password - :param string $hash: Password hash - :returns: TRUE if the password matches the hash, FALSE if not - :rtype: bool - - For more information, please refer to the `PHP manual for - password_verify() <http://php.net/password_verify>`_. - -********************* -Hash (Message Digest) -********************* - -This compatibility layer contains backports for the ``hash_equals()`` -and ``hash_pbkdf2()`` functions, which otherwise require PHP 5.6 and/or -PHP 5.5 respectively. - -Dependencies -============ - -- None - -Function reference -================== - -.. php:function:: hash_equals($known_string, $user_string) - - :param string $known_string: Known string - :param string $user_string: User-supplied string - :returns: TRUE if the strings match, FALSE otherwise - :rtype: string - - For more information, please refer to the `PHP manual for - hash_equals() <http://php.net/hash_equals>`_. - -.. php:function:: hash_pbkdf2($algo, $password, $salt, $iterations[, $length = 0[, $raw_output = FALSE]]) - - :param string $algo: Hashing algorithm - :param string $password: Password - :param string $salt: Hash salt - :param int $iterations: Number of iterations to perform during derivation - :param int $length: Output string length - :param bool $raw_output: Whether to return raw binary data - :returns: Password-derived key or FALSE on failure - :rtype: string - - For more information, please refer to the `PHP manual for - hash_pbkdf2() <http://php.net/hash_pbkdf2>`_. - -**************** -Multibyte String -**************** - -This set of compatibility functions offers limited support for PHP's -`Multibyte String extension <http://php.net/mbstring>`_. Because of -the limited alternative solutions, only a few functions are available. - -.. note:: When a character set parameter is ommited, - ``$config['charset']`` will be used. - -Dependencies -============ - -- `iconv <http://php.net/iconv>`_ extension - -.. important:: This dependency is optional and these functions will - always be declared. If iconv is not available, they WILL - fall-back to their non-mbstring versions. - -.. important:: Where a character set is supplied, it must be - supported by iconv and in a format that it recognizes. - -.. note:: For you own dependency check on the actual mbstring - extension, use the ``MB_ENABLED`` constant. - -Function reference -================== - -.. php:function:: mb_strlen($str[, $encoding = NULL]) - - :param string $str: Input string - :param string $encoding: Character set - :returns: Number of characters in the input string or FALSE on failure - :rtype: string - - For more information, please refer to the `PHP manual for - mb_strlen() <http://php.net/mb_strlen>`_. - -.. php:function:: mb_strpos($haystack, $needle[, $offset = 0[, $encoding = NULL]]) - - :param string $haystack: String to search in - :param string $needle: Part of string to search for - :param int $offset: Search offset - :param string $encoding: Character set - :returns: Numeric character position of where $needle was found or FALSE if not found - :rtype: mixed - - For more information, please refer to the `PHP manual for - mb_strpos() <http://php.net/mb_strpos>`_. - -.. php:function:: mb_substr($str, $start[, $length = NULL[, $encoding = NULL]]) - - :param string $str: Input string - :param int $start: Position of first character - :param int $length: Maximum number of characters - :param string $encoding: Character set - :returns: Portion of $str specified by $start and $length or FALSE on failure - :rtype: string - - For more information, please refer to the `PHP manual for - mb_substr() <http://php.net/mb_substr>`_. - -****************** -Standard Functions -****************** - -This set of compatibility functions offers support for a few -standard functions in PHP that otherwise require a newer PHP version. - -Dependencies -============ - -- None - -Function reference -================== - -.. php:function:: array_column(array $array, $column_key[, $index_key = NULL]) - - :param array $array: Array to fetch results from - :param mixed $column_key: Key of the column to return values from - :param mixed $index_key: Key to use for the returned values - :returns: An array of values representing a single column from the input array - :rtype: array - - For more information, please refer to the `PHP manual for - array_column() <http://php.net/array_column>`_. - -.. php:function:: hex2bin($data) - - :param array $data: Hexadecimal representation of data - :returns: Binary representation of the given data - :rtype: string - - For more information, please refer to the `PHP manual for hex2bin() - <http://php.net/hex2bin>`_. diff --git a/user_guide_src/source/general/controllers.rst b/user_guide_src/source/general/controllers.rst deleted file mode 100644 index 14e583636..000000000 --- a/user_guide_src/source/general/controllers.rst +++ /dev/null @@ -1,340 +0,0 @@ -########### -Controllers -########### - -Controllers are the heart of your application, as they determine how -HTTP requests should be handled. - -.. contents:: Page Contents - -What is a Controller? -===================== - -**A Controller is simply a class file that is named in a way that can be -associated with a URI.** - -Consider this URI:: - - example.com/index.php/blog/ - -In the above example, CodeIgniter would attempt to find a controller -named Blog.php and load it. - -**When a controller's name matches the first segment of a URI, it will -be loaded.** - -Let's try it: Hello World! -========================== - -Let's create a simple controller so you can see it in action. Using your -text editor, create a file called Blog.php, and put the following code -in it:: - - <?php - class Blog extends CI_Controller { - - public function index() - { - echo 'Hello World!'; - } - } - -Then save the file to your *application/controllers/* directory. - -.. important:: The file must be called 'Blog.php', with a capital 'B'. - -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! - -.. 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 methods. - -Methods -======= - -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 method in the -controller gets called.** - -Let's try it. Add a new method to your controller:: - - <?php - class Blog extends CI_Controller { - - public function index() - { - echo 'Hello World!'; - } - - public function comments() - { - echo 'Look at this!'; - } - } - -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 methods -==================================== - -If your URI contains more than two segments they will be passed to your -method as parameters. - -For example, let's say you have a URI like this:: - - example.com/index.php/products/shoes/sandals/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; - } - } - -.. important:: If you are using the :doc:`URI Routing <routing>` - feature, the segments passed to your method will be the re-routed - ones. - -Defining a Default Controller -============================= - -CodeIgniter can be told to load a default controller when a URI is not -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'; - -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. - -For more information, please refer to the "Reserved Routes" section of the -:doc:`URI Routing <routing>` documentation. - -Remapping Method Calls -====================== - -As noted above, the second segment of the URI typically determines which -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... - } - -.. 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 method - is called, allowing you to define your own method routing rules. - -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(); - } - } - -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>`_ -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(); - } - -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 method named ``_output()`` -to your controller that will receive the finalized output data. - -.. 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; - } - -.. 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); - } - - 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 methods -=============== - -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 - } - -Trying to access it via the URL, like this, will not work:: - - example.com/index.php/blog/_utility/ - -.. 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 want to hierarchically -organize or structure your controllers into sub-directories. CodeIgniter -permits you to do this. - -Simply create sub-directories under the main *application/controllers/* -one and place your controller classes within them. - -.. note:: When using this feature the first segment of your URI must - specify the folder. For example, let's say you have a controller located - here:: - - application/controllers/products/Shoes.php - - To call the above controller your URI will look something like this:: - - example.com/index.php/products/shoes/show/123 - -Each of your sub-directories may contain a default controller which will be -called if the URL contains *only* the sub-directory. Simply put a controller -in there that matches the name of your 'default_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. - -Class Constructors -================== - -If you intend to use a constructor in any of your Controllers, you -**MUST** place the following line of code in it:: - - parent::__construct(); - -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 - } - } - -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 method names -===================== - -Since your controller classes will extend the main application -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. diff --git a/user_guide_src/source/general/core_classes.rst b/user_guide_src/source/general/core_classes.rst deleted file mode 100644 index 9ccded75c..000000000 --- a/user_guide_src/source/general/core_classes.rst +++ /dev/null @@ -1,117 +0,0 @@ -############################ -Creating Core System Classes -############################ - -Every time CodeIgniter runs there are several base classes that are -initialized automatically as part of the core framework. It is possible, -however, to swap any of the core system classes with your own versions -or even extend the core versions. - -**Most users will never have any need to do this, but the option to -replace or extend them does exist for those who would like to -significantly alter the CodeIgniter core.** - -.. note:: Messing with a core system class has a lot of implications, so - make sure you know what you are doing before attempting it. - -System Class List -================= - -The following is a list of the core system files that are invoked every -time CodeIgniter runs: - -- Benchmark -- Config -- Controller -- Exceptions -- Hooks -- Input -- Language -- Loader -- Log -- Output -- Router -- Security -- URI -- Utf8 - -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:: - - application/core/some_class.php - -If this directory does not exist you can create it. - -Any file named identically to one from the list above will be used -instead of the one normally used. - -Please note that your class must use CI as a prefix. For example, if -your file is named Input.php the class will be named:: - - class CI_Input { - - } - -Extending Core Class -==================== - -If all you need to do is add some functionality to an existing library - -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: - -- The class declaration must extend the parent class. -- Your new class name and filename must be prefixed with MY\_ (this - item is configurable. See below.). - -For example, to extend the native Input class you'll create a file named -application/core/MY_Input.php, and declare your class with:: - - class MY_Input extends CI_Input { - - } - -.. note:: If you need to use a constructor in your class make sure you - extend the parent constructor:: - - class MY_Input extends CI_Input { - - public function __construct() - { - parent::__construct(); - // Your own constructor code - } - } - -**Tip:** Any functions in your class that are named identically to the -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. - -If you are extending the Controller core class, then be sure to extend -your new class in your application controller's constructors. - -:: - - class Welcome extends MY_Controller { - - 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:: - - $config['subclass_prefix'] = 'MY_'; - -Please note that all native CodeIgniter libraries are prefixed -with CI\_ so DO NOT use that as your prefix. diff --git a/user_guide_src/source/general/creating_drivers.rst b/user_guide_src/source/general/creating_drivers.rst deleted file mode 100644 index 63ac83902..000000000 --- a/user_guide_src/source/general/creating_drivers.rst +++ /dev/null @@ -1,25 +0,0 @@ -################ -Creating Drivers -################ - -Driver Directory and File Structure -=================================== - -Sample driver directory and file structure layout: - -- /application/libraries/Driver_name - - - Driver_name.php - - drivers - - - Driver_name_subclass_1.php - - 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 - named in the format returned by ``ucfirst()``. - -.. note:: The Driver library's architecture is such that - the subclasses don't extend and therefore don't inherit - properties or methods of the main driver.
\ 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 deleted file mode 100644 index 83742b619..000000000 --- a/user_guide_src/source/general/creating_libraries.rst +++ /dev/null @@ -1,260 +0,0 @@ -################## -Creating Libraries -################## - -When we use the term "Libraries" we are normally referring to the -classes that are located in the libraries directory and described in the -Class Reference of this user guide. In this case, however, we will -instead describe how you can create your own libraries within your -application/libraries directory in order to maintain separation between -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* directory. - -In summary: - -- You can create entirely new libraries. -- You can extend native libraries. -- You can replace native libraries. - -The page below explains these three concepts in detail. - -.. note:: The Database classes can not be extended or replaced with your - own classes. All other classes are able to be replaced/extended. - -Storage -======= - -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 -================== - -- File names must be capitalized. For example: Myclass.php -- Class declarations must be capitalized. For example: class Myclass -- Class names and file names must match. - -The Class File -============== - -Classes should have this basic prototype:: - - <?php - defined('BASEPATH') OR exit('No direct script access allowed'); - - class Someclass { - - public function some_method() - { - } - } - -.. note:: We are using the name Someclass purely as an example. - -Using Your Class -================ - -From within any of your :doc:`Controller <controllers>` methods you -can initialize your class using the standard:: - - $this->load->library('someclass'); - -Where *someclass* is the file name, without the ".php" file extension. -You can submit the file name capitalized or lower case. CodeIgniter -doesn't care. - -Once loaded you can access your class using the lower case version:: - - $this->someclass->some_method();Â // Object instances will always be lower case - -Passing Parameters When Initializing Your Class -=============================================== - -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:: - - $params = array('type' => 'large', 'color' => 'red'); - - $this->load->library('someclass', $params); - -If you use this feature you must set up your class constructor to expect -data:: - - <?php defined('BASEPATH') OR exit('No direct script access allowed'); - - class Someclass { - - 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/* directory. Note that if you dynamically pass -parameters as described above, the config file option will not be -available. - -Utilizing CodeIgniter Resources within Your Library -=================================================== - -To access CodeIgniter's native resources within your library use the -``get_instance()`` method. This method returns the CodeIgniter super -object. - -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 -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``:: - - $CI =& get_instance(); - - $CI->load->helper('url'); - $CI->load->library('session'); - $CI->config->item('base_url'); - // etc. - -.. 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. - -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 -============================================= - -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:: - - class CI_Email { - - } - -Note that most native classes are prefixed with CI\_. - -To load your library you'll see the standard loading method:: - - $this->load->library('email'); - -.. note:: At this time the Database classes can not be replaced with - your own versions. - -Extending Native Libraries -========================== - -If all you need to do is add some functionality to an existing library - -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: - -- The class declaration must extend the parent class. -- Your new class name and filename must be prefixed with MY\_ (this - 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:: - - class MY_Email extends CI_Email { - - } - -If you need to use a constructor in your class make sure you -extend the parent constructor:: - - class MY_Email extends CI_Email { - - public function __construct($config = array()) - { - parent::__construct($config); - // Your own constructor code - } - - } - -.. 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. - -Loading Your Sub-class ----------------------- - -To load your sub-class you'll use the standard syntax normally used. DO -NOT include your prefix. For example, to load the example above, which -extends the Email class, you will use:: - - $this->load->library('email'); - -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_method(); - -Setting Your Own Prefix ------------------------ - -To set your own sub-class prefix, open your -*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. diff --git a/user_guide_src/source/general/credits.rst b/user_guide_src/source/general/credits.rst deleted file mode 100644 index d0f14b3bd..000000000 --- a/user_guide_src/source/general/credits.rst +++ /dev/null @@ -1,22 +0,0 @@ -####### -Credits -####### - -CodeIgniter was originally developed by `Rick Ellis <https://ellislab.com/>`_ -(CEO of `EllisLab, Inc. <https://ellislab.com/>`_). The framework was written for -performance in the real world, with many of the class libraries, helpers, and -sub-systems borrowed from the code-base of `ExpressionEngine -<https://ellislab.com/expressionengine>`_. - -It was, for years, developed and maintained by EllisLab, the ExpressionEngine -Development Team and a group of community members called the Reactor Team. - -In 2014, CodeIgniter was acquired by the `British Columbia Institute of Technology -<http://www.bcit.ca/>`_ and was then officially announced as a community-maintained -project. - -Bleeding edge development is spearheaded by the handpicked contributors -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.
\ No newline at end of file diff --git a/user_guide_src/source/general/drivers.rst b/user_guide_src/source/general/drivers.rst deleted file mode 100644 index b64b0e75e..000000000 --- a/user_guide_src/source/general/drivers.rst +++ /dev/null @@ -1,40 +0,0 @@ -######################### -Using CodeIgniter Drivers -######################### - -Drivers are a special type of Library that has a parent class and any -number of potential child classes. Child classes have access to the -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/* 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 method:: - - $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:: - - $this->load->driver('some_parent'); - -Methods of that class can then be invoked with:: - - $this->some_parent->some_method(); - -The child classes, the drivers themselves, can then be called directly -through the parent class, without initializing them:: - - $this->some_parent->child_one->some_method(); - $this->some_parent->child_two->another_method(); - -Creating Your Own Drivers -========================= - -Please read the section of the user guide that discusses how to :doc:`create -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 deleted file mode 100644 index ac6f3235e..000000000 --- a/user_guide_src/source/general/environments.rst +++ /dev/null @@ -1,52 +0,0 @@ -############################## -Handling Multiple Environments -############################## - -Developers often desire different system behavior depending on whether -an application is running in a development or production environment. -For example, verbose error output is something that would be useful -while developing an application, but it may also pose a security issue -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 -'development'. At the top of index.php, you will see:: - - define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development'); - -This server variable can be set in your .htaccess file, or Apache -config using `SetEnv <https://httpd.apache.org/docs/2.2/mod/mod_env.html#setenv>`_. -Alternative methods are available for nginx and other servers, or you can -remove this logic entirely and set the constant based on the server's IP address. - -In addition to affecting some basic framework behavior (see the next -section), you may use this constant in your own development to -differentiate between which environment you are running in. - -Effects On Default Framework Behavior -===================================== - -There are some places in the CodeIgniter system where the ENVIRONMENT -constant is used. This section describes how default framework behavior -is affected. - -Error Reporting ---------------- - -Setting the ENVIRONMENT constant to a value of 'development' will cause -all PHP errors to be rendered to the browser when they occur. -Conversely, setting the constant to 'production' will disable all error -output. Disabling error reporting in production is a :doc:`good security -practice <security>`. - -Configuration Files -------------------- - -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 :doc:`Config Class -<../libraries/config>` 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 deleted file mode 100644 index a1cc3517a..000000000 --- a/user_guide_src/source/general/errors.rst +++ /dev/null @@ -1,120 +0,0 @@ -############## -Error Handling -############## - -CodeIgniter lets you build error reporting into your applications using -the functions described below. In addition, it has an error logging -class that permits error and debugging messages to be saved as text -files. - -.. note:: By default, CodeIgniter displays all PHP errors. You might - wish to change this behavior once your development is complete. You'll - find the error_reporting() function located at the top of your main - index.php file. Disabling error reporting will NOT prevent log files - from being written if there are errors. - -Unlike most systems in CodeIgniter, the error functions are simple -procedural interfaces that are available globally throughout the -application. This approach permits error messages to get triggered -without having to worry about class/function scoping. - -CodeIgniter also returns a status code whenever a portion of the core -calls ``exit()``. This exit status code is separate from the HTTP status -code, and serves as a notice to other processes that may be watching of -whether the script completed successfully, or if not, what kind of -problem it encountered that caused it to abort. These values are -defined in *application/config/constants.php*. While exit status codes -are most useful in CLI settings, returning the proper code helps server -software keep track of your scripts and the health of your application. - -The following functions let you generate errors: - -.. 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 - :rtype: void - - This function will display the error message supplied to it using - the error template appropriate to your execution:: - - application/views/errors/html/error_general.php - - or: - - application/views/errors/cli/error_general.php - - The optional parameter ``$status_code`` determines what HTTP status - code should be sent with the error. If ``$status_code`` is less - than 100, the HTTP status code will be set to 500, and the exit - status code will be set to ``$status_code + EXIT__AUTO_MIN``. - If that value is larger than ``EXIT__AUTO_MAX``, or if - ``$status_code`` is 100 or higher, the exit status code will be set - to ``EXIT_ERROR``. - You can check in *application/config/constants.php* for more detail. - -.. php:function:: show_404($page = '', $log_error = TRUE) - - :param string $page: URI string - :param bool $log_error: Whether to log the error - :rtype: void - - This function will display the 404 error message supplied to it - using the error template appropriate to your execution:: - - application/views/errors/html/error_404.php - - or: - - application/views/errors/cli/error_404.php - - The function expects the string passed to it to be the file path to - the page that isn't found. The exit status code will be set to - ``EXIT_UNKNOWN_FILE``. - Note that CodeIgniter automatically shows 404 messages if - controllers are not found. - - CodeIgniter automatically logs any ``show_404()`` calls. Setting the - optional second parameter to FALSE will skip logging. - -.. php:function:: log_message($level, $message) - - :param string $level: Log level: 'error', 'debug' or 'info' - :param string $message: Message to log - :rtype: 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:: - - if ($some_var == '') - { - log_message('error', 'Some variable did not contain a value.'); - } - else - { - log_message('debug', 'Some variable was correctly set'); - } - - log_message('info', 'The purpose of some variable is to provide some value.'); - - There are three message types: - - #. Error Messages. These are actual errors, such as PHP errors or - user errors. - #. Debug Messages. These are messages that assist in debugging. For - example, if a class has been initialized, you could log this as - debugging info. - #. Informational Messages. These are the lowest priority messages, - simply giving information regarding some process. - - .. 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. diff --git a/user_guide_src/source/general/helpers.rst b/user_guide_src/source/general/helpers.rst deleted file mode 100644 index d171aa8ed..000000000 --- a/user_guide_src/source/general/helpers.rst +++ /dev/null @@ -1,145 +0,0 @@ -################ -Helper Functions -################ - -Helpers, as the name suggests, help you with tasks. Each helper file is -simply a collection of functions in a particular category. There are **URL -Helpers**, that assist in creating links, there are Form Helpers that help -you create form elements, **Text Helpers** perform various text formatting -routines, **Cookie Helpers** set and read cookies, File Helpers help you -deal with files, etc. - -Unlike most other systems in CodeIgniter, Helpers are not written in an -Object Oriented format. They are simple, procedural functions. Each -helper function performs one specific task, with no dependence on other -functions. - -CodeIgniter does not load Helper Files by default, so the first step in -using a Helper is to load it. Once loaded, it becomes globally available -in your :doc:`controller <../general/controllers>` and -:doc:`views <../general/views>`. - -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/* directory. - -Loading a Helper -================ - -Loading a helper file is quite simple using the following method:: - - $this->load->helper('name'); - -Where **name** is the file name of the helper, without the .php file -extension or the "helper" part. - -For example, to load the **URL Helper** file, which is named -**url_helper.php**, you would do this:: - - $this->load->helper('url'); - -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 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 -======================== - -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') - ); - -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** -file and adding the helper to the autoload array. - -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:: - - <?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/method you wish to link to. - -"Extending" Helpers -=================== - -To "extend" Helpers, create a file in your **application/helpers/** folder -with an identical name to the existing Helper, but prefixed with **MY\_** -(this item is configurable. See below.). - -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. - -.. 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 -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; - } - } - - 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); - } - -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 -**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. - -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.
\ No newline at end of file diff --git a/user_guide_src/source/general/hooks.rst b/user_guide_src/source/general/hooks.rst deleted file mode 100644 index 6cc3407a3..000000000 --- a/user_guide_src/source/general/hooks.rst +++ /dev/null @@ -1,127 +0,0 @@ -#################################### -Hooks - Extending the Framework Core -#################################### - -CodeIgniter's Hooks feature provides a means to tap into and modify the -inner workings of the framework without hacking the core files. When -CodeIgniter runs it follows a specific execution process, diagramed in -the :doc:`Application Flow <../overview/appflow>` page. There may be -instances, however, where you'd like to cause some action to take place -at a particular stage in the execution process. For example, you might -want to run a script right before your controllers get loaded, or right -after, or you might want to trigger one of your own scripts in some -other location. - -Enabling Hooks -============== - -The hooks feature can be globally enabled/disabled by setting the -following item in the **application/config/config.php** file:: - - $config['enable_hooks'] = TRUE; - -Defining a Hook -=============== - -Hooks are defined in the **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') - ); - -**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 -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 (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/* - 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. - -You can also use lambda/anoymous functions (or closures) as hooks, with -a simpler syntax:: - - $hook['post_controller'] = function() - { - /* do something here */ - }; - -Multiple Calls to the Same Hook -=============================== - -If want to use the same hook point with more than one script, simply -make your array declaration multi-dimensional, like this:: - - $hook['pre_controller'][] = array( - 'class' => 'MyClass', - 'function' => 'MyMethod', - 'filename' => 'Myclass.php', - 'filepath' => 'hooks', - 'params' => array('beer', 'wine', 'snacks') - ); - - $hook['pre_controller'][] = array( - 'class' => 'MyOtherClass', - 'function' => 'MyOtherMethod', - 'filename' => 'Myotherclass.php', - 'filepath' => 'hooks', - 'params' => array('red', 'yellow', 'blue') - ); - -Notice the brackets after each array index:: - - $hook['pre_controller'][] - -This permits you to have the same hook point with multiple scripts. The -order you define your array will be the execution order. - -Hook Points -=========== - -The following is a list of available hook points. - -- **pre_system** - Called very early during system execution. Only the benchmark and - hooks class have been loaded at this point. No routing or other - processes have happened. -- **pre_controller** - Called immediately prior to any of your controllers being called. - All base classes, routing, and security checks have been done. -- **post_controller_constructor** - Called immediately after your controller is instantiated, but prior - to any method calls happening. -- **post_controller** - Called immediately after your controller is fully executed. -- **display_override** - 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 - then the finalized data will be available by calling - ``$this->CI->output->get_output()``. -- **cache_override** - 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.
\ No newline at end of file diff --git a/user_guide_src/source/general/index.rst b/user_guide_src/source/general/index.rst deleted file mode 100644 index 195c4a98a..000000000 --- a/user_guide_src/source/general/index.rst +++ /dev/null @@ -1,33 +0,0 @@ -############## -General Topics -############## - -.. toctree:: - :titlesonly: - - urls - controllers - reserved_names - views - models - Helpers <helpers> - libraries - creating_libraries - drivers - creating_drivers - core_classes - ancillary_classes - hooks - autoloader - common_functions - compatibility_functions - routing - errors - Caching <caching> - profiling - cli - managing_apps - environments - alternative_php - security - 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 deleted file mode 100644 index 9bbda51bb..000000000 --- a/user_guide_src/source/general/libraries.rst +++ /dev/null @@ -1,32 +0,0 @@ -########################### -Using CodeIgniter Libraries -########################### - -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 method:: - - $this->load->library('class_name'); - -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'); - -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 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>`.
\ No newline at end of file diff --git a/user_guide_src/source/general/managing_apps.rst b/user_guide_src/source/general/managing_apps.rst deleted file mode 100644 index 4861ba71a..000000000 --- a/user_guide_src/source/general/managing_apps.rst +++ /dev/null @@ -1,61 +0,0 @@ -########################## -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/* -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 directory. - -Renaming the Application Directory -================================== - -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:: - - $application_folder = 'application'; - -Relocating your Application Directory -===================================== - -It is possible to move your application directory to a different -location on your server than your web root. 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'; - -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 directory into their own sub-directory. - -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/ - applications/foo/controllers/ - applications/foo/libraries/ - applications/foo/models/ - applications/foo/views/ - applications/bar/ - applications/bar/config/ - applications/bar/controllers/ - applications/bar/libraries/ - applications/bar/models/ - 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 -example, to select the "foo" application for use you would do this:: - - $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.
\ No newline at end of file diff --git a/user_guide_src/source/general/models.rst b/user_guide_src/source/general/models.rst deleted file mode 100644 index 0b20164e9..000000000 --- a/user_guide_src/source/general/models.rst +++ /dev/null @@ -1,167 +0,0 @@ -###### -Models -###### - -Models are **optionally** available for those who want to use a more -traditional MVC approach. - -.. contents:: Page Contents - -What is a Model? -================ - -Models are PHP classes that are designed to work with information in -your database. For example, let's say you use CodeIgniter to manage a -blog. You might have a model class that contains functions to insert, -update, and retrieve your blog data. Here is an example of what such a -model class might look like:: - - class Blog_model extends CI_Model { - - public $title; - public $content; - public $date; - - 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 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`` - directly. This is generally bad practice, and a more common approach - 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/** directory. -They can be nested within sub-directories if you want this type of -organization. - -The basic prototype for a model class is this:: - - class Model_name extends CI_Model { - - } - -Where **Model_name** is the name of your class. Class names **must** have -the first letter capitalized with the rest of the name lowercase. Make -sure your class extends the base Model class. - -The file name must match the class name. For example, if this is your class:: - - class User_model extends CI_Model { - - } - -Your file will be this:: - - application/models/User_model.php - -Loading a Model -=============== - -Your models will typically be loaded and called from within your -: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-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'); - -Once loaded, you will access your model methods using an object with the -same name as your class:: - - $this->load->model('model_name'); - - $this->model_name->method(); - -If you would like your model assigned to a different object name you can -specify it via the second parameter of the loading method:: - - $this->load->model('model_name', 'foobar'); - - $this->foobar->method(); - -Here is an example of a controller, that loads a model, then serves a -view:: - - class Blog_controller extends CI_Controller { - - public function blog() - { - $this->load->model('blog'); - - $data['query'] = $this->blog->get_last_ten_entries(); - - $this->load->view('blog', $data); - } - } - - -Auto-loading Models -=================== - -If you find that you need a particular model 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** file and adding the model to the -autoload array. - -Connecting to your Database -=========================== - -When a model is loaded it does **NOT** connect automatically to your -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 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); - -- You can manually pass database connectivity settings via the third - parameter:: - - $config['hostname'] = 'localhost'; - $config['username'] = 'myusername'; - $config['password'] = 'mypassword'; - $config['database'] = 'mydatabase'; - $config['dbdriver'] = 'mysqli'; - $config['dbprefix'] = ''; - $config['pconnect'] = FALSE; - $config['db_debug'] = TRUE; - - $this->load->model('model_name', '', $config); diff --git a/user_guide_src/source/general/profiling.rst b/user_guide_src/source/general/profiling.rst deleted file mode 100644 index 2716d1781..000000000 --- a/user_guide_src/source/general/profiling.rst +++ /dev/null @@ -1,90 +0,0 @@ -########################## -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 -useful during development in order to help with debugging and -optimization. - -Initializing the Class -====================== - -.. important:: This class does NOT need to be initialized. It is loaded - 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 line anywhere within your -:doc:`Controller <controllers>` methods:: - - $this->output->enable_profiler(TRUE); - -When enabled a report will be generated and inserted at the bottom of -your pages. - -To disable the profiler you will use:: - - $this->output->enable_profiler(FALSE); - -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 the -:doc:`Benchmark Library <../libraries/benchmark>` page. - -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. - -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 Library <../libraries/output>`:: - - $sections = array( - 'config' => TRUE, - 'queries' => TRUE - ); - - $this->output->set_profiler_sections($sections); - -Available sections and the array key used to access them are described -in the table below. - -======================= =================================================================== ======== -Key Description Default -======================= =================================================================== ======== -**benchmarks** Elapsed time of Benchmark points and total execution time TRUE -**config** CodeIgniter Config variables TRUE -**controller_info** The Controller class and method requested TRUE -**get** Any GET data passed in the request TRUE -**http_headers** The HTTP headers for the current request TRUE -**memory_usage** Amount of memory consumed by the current request, in bytes TRUE -**post** Any POST data passed in the request TRUE -**queries** Listing of all database queries executed, including execution time TRUE -**uri_string** The URI of the current request TRUE -**session_data** Data stored in the current session TRUE -**query_toggle_count** The number of queries after which the query block will default to 25 - hidden. -======================= =================================================================== ======== - -.. note:: Disabling the :doc:`save_queries </database/configuration>` setting in - your database configuration will also effectively disable profiling for - database queries and render the 'queries' setting above useless. You can - optionally override this setting with ``$this->db->save_queries = TRUE;``. - Without this setting you won't be able to view the queries or the - `last_query <database/helpers>`.
\ No newline at end of file diff --git a/user_guide_src/source/general/requirements.rst b/user_guide_src/source/general/requirements.rst deleted file mode 100644 index f2729f3d5..000000000 --- a/user_guide_src/source/general/requirements.rst +++ /dev/null @@ -1,21 +0,0 @@ -################### -Server Requirements -################### - -`PHP <http://php.net/>`_ version 5.6 or newer is recommended. - -It should work on 5.3.7 as well, but we strongly advise you NOT to run -such old versions of PHP, because of potential security and performance -issues, as well as missing features. - -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 deleted file mode 100644 index 5d745cba6..000000000 --- a/user_guide_src/source/general/reserved_names.rst +++ /dev/null @@ -1,88 +0,0 @@ -############## -Reserved Names -############## - -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 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: - -- CI_Controller -- Default -- index - -Functions ---------- - -- :php:func:`is_php()` -- :php:func:`is_really_writable()` -- ``load_class()`` -- ``is_loaded()`` -- ``get_config()`` -- :php:func:`config_item()` -- :php:func:`show_error()` -- :php:func:`show_404()` -- :php:func:`log_message()` -- :php:func:`set_status_header()` -- :php:func:`get_mimes()` -- :php:func:`html_escape()` -- :php:func:`remove_invisible_characters()` -- :php:func:`is_https()` -- :php:func:`function_usable()` -- :php:func:`get_instance()` -- ``_error_handler()`` -- ``_exception_handler()`` -- ``_stringify_attributes()`` - -Variables ---------- - -- ``$config`` -- ``$db`` -- ``$lang`` - -Constants ---------- - -- ENVIRONMENT -- FCPATH -- SELF -- BASEPATH -- APPPATH -- VIEWPATH -- CI_VERSION -- MB_ENABLED -- ICONV_ENABLED -- UTF8_ENABLED -- FILE_READ_MODE -- FILE_WRITE_MODE -- DIR_READ_MODE -- DIR_WRITE_MODE -- FOPEN_READ -- FOPEN_READ_WRITE -- FOPEN_WRITE_CREATE_DESTRUCTIVE -- FOPEN_READ_WRITE_CREATE_DESTRUCTIVE -- FOPEN_WRITE_CREATE -- FOPEN_READ_WRITE_CREATE -- FOPEN_WRITE_CREATE_STRICT -- FOPEN_READ_WRITE_CREATE_STRICT -- SHOW_DEBUG_BACKTRACE -- EXIT_SUCCESS -- EXIT_ERROR -- EXIT_CONFIG -- EXIT_UNKNOWN_FILE -- EXIT_UNKNOWN_CLASS -- EXIT_UNKNOWN_METHOD -- EXIT_USER_INPUT -- EXIT_DATABASE -- EXIT__AUTO_MIN -- EXIT__AUTO_MAX
\ No newline at end of file diff --git a/user_guide_src/source/general/routing.rst b/user_guide_src/source/general/routing.rst deleted file mode 100644 index 909289d8d..000000000 --- a/user_guide_src/source/general/routing.rst +++ /dev/null @@ -1,207 +0,0 @@ -########### -URI Routing -########### - -Typically there is a one-to-one relationship between a URL string and -its corresponding controller class/method. The segments in a URI -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/method can be called instead of the one -corresponding to the URL. - -For example, let's 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/ - -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. - -Wildcards -========= - -A typical wildcard route might look something like this:: - - $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 -above example, if the literal word "product" is found in the first -segment of the URL, and a number is found in the second segment, the -"catalog" class and the "product_lookup" method are instead used. - -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 (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'; - -A URL containing the word "journals" in the first segment will be -remapped to the "blogs" class. - -:: - - $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'; - -A URL with "product" as the first segment, and anything in the second -will be remapped to the "catalog" class and the "product_lookup" -method. - -:: - - $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 method. - -.. important:: Do not use leading/trailing slashes. - -Regular Expressions -=================== - -If you prefer you can use regular expressions to define your routing -rules. Any valid regular expression is allowed, as are back-references. - -.. note:: If you use back-references you must use the dollar syntax - rather than the double backslash syntax. - -A typical RegEx route might look something like this:: - - $route['products/([a-z]+)/(\d+)'] = '$1/id_$2'; - -In the above example, a URI similar to products/shirts/123 would instead -call the "shirts" controller class and the "id_123" method. - -With regular expressions, you can also catch multiple segments at once. -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'; - -.. note:: In the above example, if the ``$1`` placeholder contains a - slash, it will still be split into multiple parameters when - passed to ``Auth::login()``. - -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 -========= - -You can also use callbacks in place of the normal routing rules to process -the back-references. Example:: - - $route['products/([a-zA-Z]+)/edit/(\d+)'] = function ($product_type, $id) - { - return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id; - }; - -Using HTTP verbs in routes -========================== - -It is possible to use HTTP verbs (request method) to define your routing rules. -This is particularly useful when building RESTful applications. You can use standard HTTP -verbs (GET, PUT, POST, DELETE, PATCH) or a custom one such (e.g. PURGE). HTTP verb rules -are case-insensitive. All you need to do is to add the verb as an array key to your route. -Example:: - - $route['products']['put'] = 'product/insert'; - -In the above example, a PUT request to URI "products" would call the ``Product::insert()`` -controller method. - -:: - - $route['products/(:num)']['DELETE'] = 'product/delete/$1'; - -A DELETE request to URL with "products" as first the segment and a number in the second will be -mapped to the ``Product::delete()`` method, passing the numeric value as the first parameter. - -Using HTTP verbs is of course, optional. - -Reserved Routes -=============== - -There are three reserved routes:: - - $route['default_controller'] = 'welcome'; - -This route points to the action that should be executed if the URI contains -no data, which will be the case when people load your root URL. -The setting accepts a **controller/method** value and ``index()`` would be -the default method if you don't specify one. In the above example, it is -``Welcome::index()`` that would be called. - -.. note:: You can NOT use a directory as a part of this setting! - -You are encouraged to always have a default route as otherwise a 404 page -will appear by default. - -:: - - $route['404_override'] = ''; - -This route indicates which controller class should be loaded if the -requested controller is not found. It will override the default 404 -error page. Same per-directory rules as with 'default_controller' -apply here as well. - -It won't affect to the ``show_404()`` function, which will -continue loading the default *error_404.php* file at -*application/views/errors/error_404.php*. - -:: - - $route['translate_uri_dashes'] = FALSE; - -As evident by the boolean value, this is not exactly a route. This -option enables you to automatically replace dashes ('-') with -underscores in the controller and method URI segments, thus saving you -additional route entries if you need to do that. -This is required, because the dash isn't a valid class or method name -character and would cause a fatal error if you try to use it. diff --git a/user_guide_src/source/general/security.rst b/user_guide_src/source/general/security.rst deleted file mode 100644 index 744a2c934..000000000 --- a/user_guide_src/source/general/security.rst +++ /dev/null @@ -1,200 +0,0 @@ -######## -Security -######## - -This page describes some "best practices" regarding web security, and -details CodeIgniter's internal security features. - -.. note:: If you came here looking for a security contact, please refer to - our `Contribution Guide <../contributing/index>`. - -URI Security -============ - -CodeIgniter is fairly restrictive regarding which characters it allows -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 (latin characters only) -- Tilde: ~ -- Percent sign: % -- Period: . -- Colon: : -- Underscore: \_ -- Dash: - -- Space - -Register_globals -================ - -During system initialization all global variables that are found to exist -in the ``$_GET``, ``$_POST``, ``$_REQUEST`` and ``$_COOKIE`` are unset. - -The unsetting routine is effectively the same as *register_globals = off*. - -display_errors -============== - -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. - -magic_quotes_runtime -==================== - -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. - -************** -Best Practices -************** - -Before accepting any data into your application, whether it be POST data -from a form submission, COOKIE data, URI data, XML-RPC data, or even -data from the SERVER array, you are encouraged to practice this three -step approach: - -#. Validate the data to ensure it conforms to the correct type, length, - size, etc. -#. Filter the data as if it were tainted. -#. Escape the data before submitting it into your database or outputting - it to a browser. - -CodeIgniter provides the following functions and tips to assist you -in this process: - -XSS Filtering -============= - -CodeIgniter comes with a Cross Site Scripting filter. This filter -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>`. - -.. note:: XSS filtering should *only be performed on output*. Filtering - input data may modify the data in undesirable ways, including - stripping special characters from passwords, which reduces - security instead of improving it. - -CSRF protection -=============== - -CSRF stands for Cross-Site Request Forgery, which is the process of an -attacker tricking their victim into unknowingly submitting a request. - -CodeIgniter provides CSRF protection out of the box, which will get -automatically triggered for every non-GET HTTP request, but also needs -you to create your submit forms in a certain way. This is explained in -the :doc:`Security Library <../libraries/security>` documentation. - -Password handling -================= - -It is *critical* that you handle passwords in your application properly. - -Unfortunately, many developers don't know how to do that, and the web is -full of outdated or otherwise wrongful advices, which doesn't help. - -We would like to give you a list of combined do's and don'ts to help you -with that. Please read below. - -- DO NOT store passwords in plain-text format. - - Always **hash** your passwords. - -- DO NOT use Base64 or similar encoding for storing passwords. - - This is as good as storing them in plain-text. Really. Do **hashing**, - not *encoding*. - - Encoding, and encryption too, are two-way processes. Passwords are - secrets that must only be known to their owner, and thus must work - only in one direction. Hashing does that - there's *no* un-hashing or - de-hashing, but there is decoding and decryption. - -- DO NOT use weak or broken hashing algorithms like MD5 or SHA1. - - These algorithms are old, proven to be flawed, and not designed for - password hashing in the first place. - - Also, DON'T invent your own algorithms. - - Only use strong password hashing algorithms like BCrypt, which is used - in PHP's own `Password Hashing <http://php.net/password>`_ functions. - - Please use them, even if you're not running PHP 5.5+, CodeIgniter - provides them for you. - -- DO NOT ever display or send a password in plain-text format! - - Even to the password's owner, if you need a "Forgotten password" - feature, just randomly generate a new, one-time (this is also important) - password and send that instead. - -- DO NOT put unnecessary limits on your users' passwords. - - If you're using a hashing algorithm other than BCrypt (which has a limit - of 72 characters), you should set a relatively high limit on password - lengths in order to mitigate DoS attacks - say, 1024 characters. - - Other than that however, there's no point in forcing a rule that a - password can only be up to a number of characters, or that it can't - contain a certain set of special characters. - - Not only does this **reduce** security instead of improving it, but - there's literally no reason to do it. No technical limitations and - no (practical) storage constraints apply once you've hashed them, none! - -Validate input data -=================== - -CodeIgniter has a :doc:`Form Validation Library -<../libraries/form_validation>` that assists you in -validating, filtering, and prepping your data. - -Even if that doesn't work for your use case however, be sure to always -validate and sanitize all input data. For example, if you expect a numeric -string for an input variable, you can check for that with ``is_numeric()`` -or ``ctype_digit()``. Always try to narrow down your checks to a certain -pattern. - -Have it in mind that this includes not only ``$_POST`` and ``$_GET`` -variables, but also cookies, the user-agent string and basically -*all data that is not created directly by your own code*. - - -Escape all data before database insertion -========================================= - -Never insert information into your database without escaping it. -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. diff --git a/user_guide_src/source/general/styleguide.rst b/user_guide_src/source/general/styleguide.rst deleted file mode 100644 index 9b4a84e14..000000000 --- a/user_guide_src/source/general/styleguide.rst +++ /dev/null @@ -1,636 +0,0 @@ -############### -PHP Style Guide -############### - - -The following page describes the coding styles adhered to when -contributing to the development of CodeIgniter. There is no requirement -to use these styles in your own CodeIgniter application, though they -are recommended. - -.. contents:: Table of Contents - -File Format -=========== - -Files should be saved with Unicode (UTF-8) encoding. The BOM should -*not* be used. Unlike UTF-16 and UTF-32, there's no byte order to -indicate in a UTF-8 encoded file, and the BOM can have a negative side -effect in PHP of sending output, preventing the application from being -able to set its own headers. Unix line endings should be used (LF). - -Here is how to apply these settings in some of the more common text -editors. Instructions for your text editor may vary; check your text -editor's documentation. - -TextMate -'''''''' - -#. Open the Application Preferences -#. Click Advanced, and then the "Saving" tab -#. In "File Encoding", select "UTF-8 (recommended)" -#. In "Line Endings", select "LF (recommended)" -#. *Optional:* Check "Use for existing files as well" if you wish to - modify the line endings of files you open to your new preference. - -BBEdit -'''''' - -#. Open the Application Preferences -#. Select "Text Encodings" on the left. -#. In "Default text encoding for new documents", select "Unicode (UTF-8, - no BOM)" -#. *Optional:* In "If file's encoding can't be guessed, use", select - "Unicode (UTF-8, no BOM)" -#. Select "Text Files" on the left. -#. In "Default line breaks", select "Mac OS X and Unix (LF)" - -PHP Closing Tag -=============== - -The PHP closing tag on a PHP document **?>** is optional to the PHP -parser. However, if used, any whitespace following the closing tag, -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 MUST OMIT the PHP closing -tag and end with a single empty line instead. - -File Naming -=========== - -Class files must be named in a Ucfirst-like manner, while any other file name -(configurations, views, generic scripts, etc.) should be in all lowercase. - -**INCORRECT**:: - - somelibrary.php - someLibrary.php - SOMELIBRARY.php - Some_Library.php - - Application_config.php - Application_Config.php - applicationConfig.php - -**CORRECT**:: - - Somelibrary.php - Some_library.php - - applicationconfig.php - application_config.php - -Furthermore, class file names should match the name of the class itself. -For example, if you have a class named `Myclass`, then its filename must -be **Myclass.php**. - -Class and Method Naming -======================= - -Class names should always start with an uppercase letter. Multiple words -should be separated with an underscore, and not CamelCased. - -**INCORRECT**:: - - class superclass - class SuperClass - -**CORRECT**:: - - class Super_class - -:: - - class Super_class { - - public function __construct() - { - - } - } - -Class methods should be entirely lowercased and named to clearly -indicate their function, preferably including a verb. Try to avoid -overly long and verbose names. Multiple words should be separated -with an underscore. - -**INCORRECT**:: - - function fileproperties() // not descriptive and needs underscore separator - function fileProperties() // not descriptive and uses CamelCase - function getfileproperties() // Better! But still missing underscore separator - function getFileProperties() // uses CamelCase - function get_the_file_properties_from_the_file() // wordy - -**CORRECT**:: - - function get_file_properties() // descriptive, underscore separator, and all lowercase letters - -Variable Names -============== - -The guidelines for variable naming are very similar to those used for -class methods. Variables should contain only lowercase letters, -use underscore separators, and be reasonably named to indicate their -purpose and contents. Very short, non-word variables should only be used -as iterators in for() loops. - -**INCORRECT**:: - - $j = 'foo'; // single letter variables should only be used in for() loops - $Str // contains uppercase letters - $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning - $groupid // multiple words, needs underscore separator - $name_of_last_city_used // too long - -**CORRECT**:: - - for ($j = 0; $j < 10; $j++) - $str - $buffer - $group_id - $last_city - -Commenting -========== - -In general, code should be commented prolifically. It not only helps -describe the flow and intent of the code for less experienced -programmers, but can prove invaluable when returning to your own code -months down the line. There is not a required format for comments, but -the following are recommended. - -`DocBlock <http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.docblock>`_ -style comments preceding class, method, and property declarations so they can be -picked up by IDEs:: - - /** - * Super Class - * - * @package Package Name - * @subpackage Subpackage - * @category Category - * @author Author Name - * @link http://example.com - */ - class Super_class { - -:: - - /** - * Encodes string for use in XML - * - * @param string $str Input string - * @return string - */ - function xml_encode($str) - -:: - - /** - * Data for class manipulation - * - * @var array - */ - public $data = array(); - -Use single line comments within code, leaving a blank line between large -comment blocks and code. - -:: - - // break up the string by newlines - $parts = explode("\n", $str); - - // A longer comment that needs to give greater detail on what is - // occurring and why can use multiple single-line comments. Try to - // keep the width reasonable, around 70 characters is the easiest to - // read. Don't hesitate to link to permanent external resources - // that may provide greater detail: - // - // http://example.com/information_about_something/in_particular/ - - $parts = $this->foo($parts); - -Constants -========= - -Constants follow the same guidelines as do variables, except constants -should always be fully uppercase. *Always use CodeIgniter constants when -appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.* - -**INCORRECT**:: - - myConstant // missing underscore separator and not fully uppercase - N // no single-letter constants - S_C_VER // not descriptive - $str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants - -**CORRECT**:: - - MY_CONSTANT - NEWLINE - SUPER_CLASS_VERSION - $str = str_replace(LD.'foo'.RD, 'bar', $str); - -TRUE, FALSE, and NULL -===================== - -**TRUE**, **FALSE**, and **NULL** keywords should always be fully -uppercase. - -**INCORRECT**:: - - if ($foo == true) - $bar = false; - function foo($bar = null) - -**CORRECT**:: - - if ($foo == TRUE) - $bar = FALSE; - function foo($bar = NULL) - -Logical Operators -================= - -Use of the ``||`` "or" comparison operator is discouraged, as its clarity -on some output devices is low (looking like the number 11, for instance). -``&&`` is preferred over ``AND`` but either are acceptable, and a space should -always precede and follow ``!``. - -**INCORRECT**:: - - if ($foo || $bar) - if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications - if (!$foo) - if (! is_array($foo)) - -**CORRECT**:: - - if ($foo OR $bar) - if ($foo && $bar) // recommended - if ( ! $foo) - if ( ! is_array($foo)) - - -Comparing Return Values and Typecasting -======================================= - -Some PHP functions return FALSE on failure, but may also have a valid -return value of "" or 0, which would evaluate to FALSE in loose -comparisons. Be explicit by comparing the variable type when using these -return values in conditionals to ensure the return value is indeed what -you expect, and not a value that has an equivalent loose-type -evaluation. - -Use the same stringency in returning and checking your own variables. -Use **===** and **!==** as necessary. - -**INCORRECT**:: - - // If 'foo' is at the beginning of the string, strpos will return a 0, - // resulting in this conditional evaluating as TRUE - if (strpos($str, 'foo') == FALSE) - -**CORRECT**:: - - if (strpos($str, 'foo') === FALSE) - -**INCORRECT**:: - - function build_string($str = "") - { - if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? - { - - } - } - -**CORRECT**:: - - function build_string($str = "") - { - if ($str === "") - { - - } - } - - -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 -other numbers) become strings of digits, and boolean TRUE becomes "1":: - - $str = (string) $str; // cast $str as a string - -Debugging Code -============== - -Do not leave debugging code in your submissions, even when commented out. -Things such as ``var_dump()``, ``print_r()``, ``die()``/``exit()`` should not be included -in your code unless it serves a specific purpose other than debugging. - -Whitespace in Files -=================== - -No whitespace can precede the opening PHP tag or follow the closing PHP -tag. Output is buffered, so whitespace in your files can cause output to -begin before CodeIgniter outputs its content, leading to errors and an -inability for CodeIgniter to send proper headers. - -Compatibility -============= - -CodeIgniter recommends PHP 5.6 or newer to be used, but it should be -compatible with PHP 5.3.7. Your code must either be compatible with this -requirement, provide a suitable fallback, or be an optional feature that -dies quietly without affecting a user's application. - -Additionally, do not use PHP functions that require non-default libraries -to be installed unless your code contains an alternative method when the -function is not available. - -One File per Class -================== - -Use separate files for each class, unless the classes are *closely related*. -An example of a CodeIgniter file that contains multiple classes is the -Xmlrpc library file. - -Whitespace -========== - -Use tabs for whitespace in your code, not spaces. This may seem like a -small thing, but using tabs instead of whitespace allows the developer -looking at your code to have indentation at levels that they prefer and -customize in whatever application they use. And as a side benefit, it -results in (slightly) more compact files, storing one tab character -versus, say, four space characters. - -Line Breaks -=========== - -Files must be saved with Unix line breaks. This is more of an issue for -developers who work in Windows, but in any case ensure that your text -editor is setup to save files with Unix line breaks. - -Code Indenting -============== - -Use Allman style indenting. With the exception of Class declarations, -braces are always placed on a line by themselves, and indented at the -same level as the control statement that "owns" them. - -**INCORRECT**:: - - function foo($bar) { - // ... - } - - foreach ($arr as $key => $val) { - // ... - } - - if ($foo == $bar) { - // ... - } else { - // ... - } - - for ($i = 0; $i < 10; $i++) - { - for ($j = 0; $j < 10; $j++) - { - // ... - } - } - - try { - // ... - } - catch() { - // ... - } - -**CORRECT**:: - - function foo($bar) - { - // ... - } - - foreach ($arr as $key => $val) - { - // ... - } - - if ($foo == $bar) - { - // ... - } - else - { - // ... - } - - for ($i = 0; $i < 10; $i++) - { - for ($j = 0; $j < 10; $j++) - { - // ... - } - } - - try - { - // ... - } - catch() - { - // ... - } - -Bracket and Parenthetic Spacing -=============================== - -In general, parenthesis and brackets should not use any additional -spaces. The exception is that a space should always follow PHP control -structures that accept arguments with parenthesis (declare, do-while, -elseif, for, foreach, if, switch, while), to help distinguish them from -functions and increase readability. - -**INCORRECT**:: - - $arr[ $foo ] = 'foo'; - -**CORRECT**:: - - $arr[$foo] = 'foo'; // no spaces around array keys - -**INCORRECT**:: - - function foo ( $bar ) - { - - } - -**CORRECT**:: - - function foo($bar) // no spaces around parenthesis in function declarations - { - - } - -**INCORRECT**:: - - foreach( $query->result() as $row ) - -**CORRECT**:: - - foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis - -Localized Text -============== - -CodeIgniter libraries should take advantage of corresponding language files -whenever possible. - -**INCORRECT**:: - - return "Invalid Selection"; - -**CORRECT**:: - - return $this->lang->line('invalid_selection'); - -Private Methods and Variables -============================= - -Methods and variables that are only accessed internally, -such as utility and helper functions that your public methods use for -code abstraction, should be prefixed with an underscore. - -:: - - 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()``. - -Make sure that your dev environment has error reporting enabled -for ALL users, and that display_errors is enabled in the PHP -environment. You can check this setting with:: - - if (ini_get('display_errors') == 1) - { - exit "Enabled"; - } - -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://php.net/manual/en/errorfunc.configuration.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. - -**INCORRECT**:: - - <? echo $foo; ?> - - <?=$foo?> - -**CORRECT**:: - - <?php echo $foo; ?> - -.. note:: PHP 5.4 will always have the **<?=** tag available. - -One Statement Per Line -====================== - -Never combine statements on one line. - -**INCORRECT**:: - - $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag); - -**CORRECT**:: - - $foo = 'this'; - $bar = 'that'; - $bat = str_replace($foo, $bar, $bag); - -Strings -======= - -Always use single quoted strings unless you need variables parsed, and -in cases where you do need variables parsed, use braces to prevent -greedy token parsing. You may also use double-quoted strings if the -string contains single quotes, so you do not have to use escape -characters. - -**INCORRECT**:: - - "My String" // no variable parsing, so no use for double quotes - "My string $foo" // needs braces - 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly - -**CORRECT**:: - - 'My String' - "My string {$foo}" - "SELECT foo FROM bar WHERE baz = 'bag'" - -SQL Queries -=========== - -SQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, -AS, JOIN, ON, IN, etc. - -Break up long queries into multiple lines for legibility, preferably -breaking for each clause. - -**INCORRECT**:: - - // keywords are lowercase and query is too long for - // a single line (... indicates continuation of line) - $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses - ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100"); - -**CORRECT**:: - - $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz - FROM exp_pre_email_addresses - WHERE foo != 'oof' - AND baz != 'zab' - ORDER BY foobaz - LIMIT 5, 100"); - -Default Function Arguments -========================== - -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)
\ No newline at end of file diff --git a/user_guide_src/source/general/urls.rst b/user_guide_src/source/general/urls.rst deleted file mode 100644 index b8a1b9f5b..000000000 --- a/user_guide_src/source/general/urls.rst +++ /dev/null @@ -1,100 +0,0 @@ -################ -CodeIgniter URLs -################ - -By default, URLs in CodeIgniter are designed to be search-engine and -human friendly. Rather than using the standard "query string" approach -to URLs that is synonymous with dynamic systems, CodeIgniter uses a -**segment-based** approach:: - - example.com/news/article/my_article - -.. note:: Query string URLs can be optionally enabled, as described - below. - -URI Segments -============ - -The segments in the URL, in following with the Model-View-Controller -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 - should be called. -#. The third, and any additional segments, represent the ID and any - variables that will be passed to the controller. - -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. - -Removing the index.php file -=========================== - -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 -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: - -.. code-block:: apache - - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteCond %{REQUEST_FILENAME} !-d - RewriteRule ^(.*)$ index.php/$1 [L] - -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:: 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 -=================== - -In your **config/config.php** file you can specify a suffix that will be -added to all URLs generated by CodeIgniter. For example, if a URL is -this:: - - example.com/index.php/products/view/shoes - -You can optionally add a suffix, like **.html,** making the page appear to -be of a certain type:: - - example.com/index.php/products/view/shoes.html - -Enabling Query Strings -====================== - -In some cases you might prefer to use query strings URLs:: - - index.php?c=products&m=view&id=345 - -CodeIgniter optionally supports this capability, which can be enabled in -your **application/config.php** file. If you open your config file you'll -see these items:: - - $config['enable_query_strings'] = FALSE; - $config['controller_trigger'] = 'c'; - $config['function_trigger'] = 'm'; - -If you change "enable_query_strings" to TRUE this feature will become -active. Your controllers and functions will then be accessible using the -"trigger" words you've set to invoke your controllers and methods:: - - 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.
\ No newline at end of file diff --git a/user_guide_src/source/general/views.rst b/user_guide_src/source/general/views.rst deleted file mode 100644 index 2fc0cb2ca..000000000 --- a/user_guide_src/source/general/views.rst +++ /dev/null @@ -1,213 +0,0 @@ -##### -Views -##### - -A view is simply a web page, or a page fragment, like a header, footer, -sidebar, etc. In fact, views can flexibly be embedded within other views -(within other views, etc., etc.) if you need this type of hierarchy. - -Views are never called directly, they must be loaded by a -:doc:`controller <controllers>`. Remember that in an MVC framework, the -Controller acts as the traffic cop, so it is responsible for fetching a -particular view. If you have not read the -:doc:`Controllers <controllers>` page you should do so before -continuing. - -Using the example controller you created in the -:doc:`controller <controllers>` page, let's add a view to it. - -Creating a View -=============== - -Using your text editor, create a file called blogview.php, and put this -in it:: - - <html> - <head> - <title>My Blog</title> - </head> - <body> - <h1>Welcome to my Blog!</h1> - </body> - </html> - -Then save the file in your *application/views/* directory. - -Loading a View -============== - -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. - -Now, open the controller file you made earlier called Blog.php, and -replace the echo statement with the view loading method:: - - <?php - class Blog extends CI_Controller { - - public function index() - { - $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:: - - example.com/index.php/blog/ - -Loading multiple views -====================== - -CodeIgniter will intelligently handle multiple calls to -``$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:: - - <?php - - class Page extends CI_Controller { - - public function index() - { - $data['page_title'] = 'Your title'; - $this->load->view('header'); - $this->load->view('menu'); - $this->load->view('content', $data); - $this->load->view('footer'); - } - - } - -In the example above, we are using "dynamically added data", which you -will see below. - -Storing Views within Sub-directories -==================================== - -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('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 method. Here -is an example using an array:: - - $data = array( - 'title' => 'My Title', - 'heading' => 'My Heading', - 'message' => 'My Message' - ); - - $this->load->view('blogview', $data); - -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. - -Let's try it with your controller file. Open it add this code:: - - <?php - class Blog extends CI_Controller { - - public function index() - { - $data['title'] = "My Real Title"; - $data['heading'] = "My Real Heading"; - - $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:: - - <html> - <head> - <title><?php echo $title;?></title> - </head> - <body> - <h1><?php echo $heading;?></h1> - </body> - </html> - -Then load the page at the URL you've been using and you should see the -variables replaced. - -Creating Loops -============== - -The data array you pass to your view files is not limited to simple -variables. You can pass multi dimensional arrays, which can be looped to -generate multiple rows. For example, if you pull data from your database -it will typically be in the form of a multi-dimensional array. - -Here's a simple example. Add this to your controller:: - - <?php - class Blog extends CI_Controller { - - public function index() - { - $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); - - $data['title'] = "My Real Title"; - $data['heading'] = "My Real Heading"; - - $this->load->view('blogview', $data); - } - } - -Now open your view file and create a loop:: - - <html> - <head> - <title><?php echo $title;?></title> - </head> - <body> - <h1><?php echo $heading;?></h1> - - <h3>My Todo List</h3> - - <ul> - <?php foreach ($todo_list as $item):?> - - <li><?php echo $item;?></li> - - <?php endforeach;?> - </ul> - - </body> - </html> - -.. 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 <alternative_php>`. - -Returning views as data -======================= - -There is a third **optional** parameter lets you change the behavior of -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 -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);
\ No newline at end of file diff --git a/user_guide_src/source/general/welcome.rst b/user_guide_src/source/general/welcome.rst deleted file mode 100644 index b6f473c2b..000000000 --- a/user_guide_src/source/general/welcome.rst +++ /dev/null @@ -1,32 +0,0 @@ -###################### -Welcome to CodeIgniter -###################### - -CodeIgniter is an Application Development Framework - a toolkit - for -people who build web sites using PHP. Its goal is to enable you to -develop projects much faster than you could if you were writing code -from scratch, by providing a rich set of libraries for commonly needed -tasks, as well as a simple interface and logical structure to access -these libraries. CodeIgniter lets you creatively focus on your project -by minimizing the amount of code needed for a given task. - -*********************** -Who is CodeIgniter For? -*********************** - -CodeIgniter is right for you if: - -- You want a framework with a small footprint. -- You need exceptional performance. -- You need broad compatibility with standard hosting accounts that run - a variety of PHP versions and configurations. -- You want a framework that requires nearly zero configuration. -- You want a framework that does not require you to use the command - line. -- You want a framework that does not require you to adhere to - restrictive coding rules. -- You are not interested in large-scale monolithic libraries like PEAR. -- 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.
\ No newline at end of file |