From 02a0518e1c56ba3506f370362ac5ebdb8a138312 Mon Sep 17 00:00:00 2001 From: Andrey Andreev Date: Sat, 13 Jan 2018 13:57:11 +0200 Subject: [ci skip] 3.1.7 release --- user_guide/libraries/benchmark.html | 703 +++++++++++ user_guide/libraries/caching.html | 895 +++++++++++++ user_guide/libraries/calendar.html | 972 +++++++++++++++ user_guide/libraries/cart.html | 1025 +++++++++++++++ user_guide/libraries/config.html | 834 +++++++++++++ user_guide/libraries/email.html | 1218 ++++++++++++++++++ user_guide/libraries/encrypt.html | 787 ++++++++++++ user_guide/libraries/encryption.html | 1405 +++++++++++++++++++++ user_guide/libraries/file_uploading.html | 1025 +++++++++++++++ user_guide/libraries/form_validation.html | 1932 +++++++++++++++++++++++++++++ user_guide/libraries/ftp.html | 1016 +++++++++++++++ user_guide/libraries/image_lib.html | 1255 +++++++++++++++++++ user_guide/libraries/index.html | 527 ++++++++ user_guide/libraries/input.html | 1191 ++++++++++++++++++ user_guide/libraries/javascript.html | 802 ++++++++++++ user_guide/libraries/language.html | 733 +++++++++++ user_guide/libraries/loader.html | 1213 ++++++++++++++++++ user_guide/libraries/migration.html | 758 +++++++++++ user_guide/libraries/output.html | 912 ++++++++++++++ user_guide/libraries/pagination.html | 784 ++++++++++++ user_guide/libraries/parser.html | 850 +++++++++++++ user_guide/libraries/security.html | 739 +++++++++++ user_guide/libraries/sessions.html | 1922 ++++++++++++++++++++++++++++ user_guide/libraries/table.html | 911 ++++++++++++++ user_guide/libraries/trackback.html | 1035 ++++++++++++++++ user_guide/libraries/typography.html | 657 ++++++++++ user_guide/libraries/unit_testing.html | 846 +++++++++++++ user_guide/libraries/uri.html | 890 +++++++++++++ user_guide/libraries/user_agent.html | 931 ++++++++++++++ user_guide/libraries/xmlrpc.html | 1151 +++++++++++++++++ user_guide/libraries/zip.html | 846 +++++++++++++ 31 files changed, 30765 insertions(+) create mode 100644 user_guide/libraries/benchmark.html create mode 100644 user_guide/libraries/caching.html create mode 100644 user_guide/libraries/calendar.html create mode 100644 user_guide/libraries/cart.html create mode 100644 user_guide/libraries/config.html create mode 100644 user_guide/libraries/email.html create mode 100644 user_guide/libraries/encrypt.html create mode 100644 user_guide/libraries/encryption.html create mode 100644 user_guide/libraries/file_uploading.html create mode 100644 user_guide/libraries/form_validation.html create mode 100644 user_guide/libraries/ftp.html create mode 100644 user_guide/libraries/image_lib.html create mode 100644 user_guide/libraries/index.html create mode 100644 user_guide/libraries/input.html create mode 100644 user_guide/libraries/javascript.html create mode 100644 user_guide/libraries/language.html create mode 100644 user_guide/libraries/loader.html create mode 100644 user_guide/libraries/migration.html create mode 100644 user_guide/libraries/output.html create mode 100644 user_guide/libraries/pagination.html create mode 100644 user_guide/libraries/parser.html create mode 100644 user_guide/libraries/security.html create mode 100644 user_guide/libraries/sessions.html create mode 100644 user_guide/libraries/table.html create mode 100644 user_guide/libraries/trackback.html create mode 100644 user_guide/libraries/typography.html create mode 100644 user_guide/libraries/unit_testing.html create mode 100644 user_guide/libraries/uri.html create mode 100644 user_guide/libraries/user_agent.html create mode 100644 user_guide/libraries/xmlrpc.html create mode 100644 user_guide/libraries/zip.html (limited to 'user_guide/libraries') diff --git a/user_guide/libraries/benchmark.html b/user_guide/libraries/benchmark.html new file mode 100644 index 000000000..5acde01bb --- /dev/null +++ b/user_guide/libraries/benchmark.html @@ -0,0 +1,703 @@ + + + + + + + + + + Benchmarking Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Benchmarking Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Benchmarking Class

+

CodeIgniter has a Benchmarking class that is always active, enabling the +time difference between any two marked points to be calculated.

+
+

Note

+

This class is initialized automatically by the system so there +is no need to do it manually.

+
+

In addition, the benchmark is always started the moment the framework is +invoked, and ended by the output class right before sending the final +view to the browser, enabling a very accurate timing of the entire +system execution to be shown.

+ +
+

Using the Benchmark Class

+

The Benchmark class can be used within your +controllers, +views, or your models. +The process for usage is this:

+
    +
  1. Mark a start point
  2. +
  3. Mark an end point
  4. +
  5. Run the “elapsed time” function to view the results
  6. +
+

Here’s an example using real code:

+
$this->benchmark->mark('code_start');
+
+// Some code happens here
+
+$this->benchmark->mark('code_end');
+
+echo $this->benchmark->elapsed_time('code_start', 'code_end');
+
+
+
+

Note

+

The words “code_start” and “code_end” are arbitrary. They +are simply words used to set two markers. You can use any words you +want, and you can set multiple sets of markers. Consider this example:

+
$this->benchmark->mark('dog');
+
+// Some code happens here
+
+$this->benchmark->mark('cat');
+
+// More code happens here
+
+$this->benchmark->mark('bird');
+
+echo $this->benchmark->elapsed_time('dog', 'cat');
+echo $this->benchmark->elapsed_time('cat', 'bird');
+echo $this->benchmark->elapsed_time('dog', 'bird');
+
+
+
+
+

Profiling Your Benchmark Points

+

If you want your benchmark data to be available to the +Profiler all of your marked points must +be set up in pairs, and each mark point name must end with _start and +_end. Each pair of points must otherwise be named identically. Example:

+
$this->benchmark->mark('my_mark_start');
+
+// Some code happens here...
+
+$this->benchmark->mark('my_mark_end');
+
+$this->benchmark->mark('another_mark_start');
+
+// Some more code happens here...
+
+$this->benchmark->mark('another_mark_end');
+
+
+

Please read the Profiler page for more +information.

+
+
+

Displaying Total Execution Time

+

If you would like to display the total elapsed time from the moment +CodeIgniter starts to the moment the final output is sent to the +browser, simply place this in one of your view templates:

+
<?php echo $this->benchmark->elapsed_time();?>
+
+
+

You’ll notice that it’s the same function used in the examples above to +calculate the time between two point, except you are not using any +parameters. When the parameters are absent, CodeIgniter does not stop +the benchmark until right before the final output is sent to the +browser. It doesn’t matter where you use the function call, the timer +will continue to run until the very end.

+

An alternate way to show your elapsed time in your view files is to use +this pseudo-variable, if you prefer not to use the pure PHP:

+
{elapsed_time}
+
+
+
+

Note

+

If you want to benchmark anything within your controller +functions you must set your own start/end points.

+
+
+
+

Displaying Memory Consumption

+

If your PHP installation is configured with –enable-memory-limit, you +can display the amount of memory consumed by the entire system using the +following code in one of your view file:

+
<?php echo $this->benchmark->memory_usage();?>
+
+
+
+

Note

+

This function can only be used in your view files. The consumption +will reflect the total memory used by the entire app.

+
+

An alternate way to show your memory usage in your view files is to use +this pseudo-variable, if you prefer not to use the pure PHP:

+
{memory_usage}
+
+
+
+
+
+

Class Reference

+
+
+class CI_Benchmark
+
+
+mark($name)
+
+++ + + + + + +
Parameters:
    +
  • $name (string) – the name you wish to assign to your marker
  • +
+
Return type:

void

+
+

Sets a benchmark marker.

+
+ +
+
+elapsed_time([$point1 = ''[, $point2 = ''[, $decimals = 4]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $point1 (string) – a particular marked point
  • +
  • $point2 (string) – a particular marked point
  • +
  • $decimals (int) – number of decimal places for precision
  • +
+
Returns:

Elapsed time

+
Return type:

string

+
+

Calculates and returns the time difference between two marked points.

+

If the first parameter is empty this function instead returns the +{elapsed_time} pseudo-variable. This permits the full system +execution time to be shown in a template. The output class will +swap the real value for this variable.

+
+ +
+
+memory_usage()
+
+++ + + + + + +
Returns:Memory usage info
Return type:string
+

Simply returns the {memory_usage} marker.

+

This permits it to be put it anywhere in a template without the memory +being calculated until the end. The Output Class will +swap the real value for this variable.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/caching.html b/user_guide/libraries/caching.html new file mode 100644 index 000000000..bb328ecc1 --- /dev/null +++ b/user_guide/libraries/caching.html @@ -0,0 +1,895 @@ + + + + + + + + + + Caching Driver — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Caching Driver

+

CodeIgniter features wrappers around some of the most popular forms of +fast and dynamic caching. All but file-based caching require specific +server requirements, and a Fatal Exception will be thrown if server +requirements are not met.

+ +
+

Example Usage

+

The following example will load the cache driver, specify APC +as the driver to use, and fall back to file-based caching if APC is not +available in the hosting environment.

+
$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
+
+if ( ! $foo = $this->cache->get('foo'))
+{
+        echo 'Saving to the cache!<br />';
+        $foo = 'foobarbaz!';
+
+        // Save into the cache for 5 minutes
+        $this->cache->save('foo', $foo, 300);
+}
+
+echo $foo;
+
+
+

You can also prefix cache item names via the key_prefix setting, which is useful +to avoid collisions when you’re running multiple applications on the same environment.

+
$this->load->driver('cache',
+        array('adapter' => 'apc', 'backup' => 'file', 'key_prefix' => 'my_')
+);
+
+$this->cache->get('foo'); // Will get the cache entry named 'my_foo'
+
+
+
+
+

Class Reference

+
+
+class CI_Cache
+
+
+is_supported($driver)
+
+++ + + + + + + + +
Parameters:
    +
  • $driver (string) – the name of the caching driver
  • +
+
Returns:

TRUE if supported, FALSE if not

+
Return type:

bool

+
+

This method is automatically called when accessing drivers via +$this->cache->get(). However, if the individual drivers are used, +make sure to call this method to ensure the driver is supported in the +hosting environment.

+
if ($this->cache->apc->is_supported())
+{
+        if ($data = $this->cache->apc->get('my_cache'))
+        {
+                // do things.
+        }
+}
+
+
+
+ +
+
+get($id)
+
+++ + + + + + + + +
Parameters:
    +
  • $id (string) – Cache item name
  • +
+
Returns:

Item value or FALSE if not found

+
Return type:

mixed

+
+

This method will attempt to fetch an item from the cache store. If the +item does not exist, the method will return FALSE.

+
$foo = $this->cache->get('my_cached_item');
+
+
+
+ +
+
+save($id, $data[, $ttl = 60[, $raw = FALSE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $id (string) – Cache item name
  • +
  • $data (mixed) – the data to save
  • +
  • $ttl (int) – Time To Live, in seconds (default 60)
  • +
  • $raw (bool) – Whether to store the raw value
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

string

+
+

This method will save an item to the cache store. If saving fails, the +method will return FALSE.

+
$this->cache->save('cache_item_id', 'data_to_cache');
+
+
+
+

Note

+

The $raw parameter is only utilized by APC and Memcache, +in order to allow usage of increment() and decrement().

+
+
+ +
+
+delete($id)
+
+++ + + + + + + + +
Parameters:
    +
  • $id (string) – name of cached item
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

This method will delete a specific item from the cache store. If item +deletion fails, the method will return FALSE.

+
$this->cache->delete('cache_item_id');
+
+
+
+ +
+
+increment($id[, $offset = 1])
+
+++ + + + + + + + +
Parameters:
    +
  • $id (string) – Cache ID
  • +
  • $offset (int) – Step/value to add
  • +
+
Returns:

New value on success, FALSE on failure

+
Return type:

mixed

+
+

Performs atomic incrementation of a raw stored value.

+
// 'iterator' has a value of 2
+
+$this->cache->increment('iterator'); // 'iterator' is now 3
+
+$this->cache->increment('iterator', 3); // 'iterator' is now 6
+
+
+
+ +
+
+decrement($id[, $offset = 1])
+
+++ + + + + + + + +
Parameters:
    +
  • $id (string) – Cache ID
  • +
  • $offset (int) – Step/value to reduce by
  • +
+
Returns:

New value on success, FALSE on failure

+
Return type:

mixed

+
+

Performs atomic decrementation of a raw stored value.

+
// 'iterator' has a value of 6
+
+$this->cache->decrement('iterator'); // 'iterator' is now 5
+
+$this->cache->decrement('iterator', 2); // 'iterator' is now 3
+
+
+
+ +
+
+clean()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

This method will ‘clean’ the entire cache. If the deletion of the +cache files fails, the method will return FALSE.

+
$this->cache->clean();
+
+
+
+ +
+
+cache_info()
+
+++ + + + + + +
Returns:Information on the entire cache database
Return type:mixed
+

This method will return information on the entire cache.

+
var_dump($this->cache->cache_info());
+
+
+
+

Note

+

The information returned and the structure of the data is dependent +on which adapter is being used.

+
+
+ +
+
+get_metadata($id)
+
+++ + + + + + + + +
Parameters:
    +
  • $id (string) – Cache item name
  • +
+
Returns:

Metadata for the cached item

+
Return type:

mixed

+
+

This method will return detailed information on a specific item in the +cache.

+
var_dump($this->cache->get_metadata('my_cached_item'));
+
+
+
+

Note

+

The information returned and the structure of the data is dependent +on which adapter is being used.

+
+
+ +
+ +
+
+

Drivers

+
+

Alternative PHP Cache (APC) Caching

+

All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:

+
$this->load->driver('cache');
+$this->cache->apc->save('foo', 'bar', 10);
+
+
+

For more information on APC, please see +http://php.net/apc.

+
+
+

File-based Caching

+

Unlike caching from the Output Class, the driver file-based caching +allows for pieces of view files to be cached. Use this with care, and +make sure to benchmark your application, as a point can come where disk +I/O will negate positive gains by caching.

+

All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:

+
$this->load->driver('cache');
+$this->cache->file->save('foo', 'bar', 10);
+
+
+
+
+

Memcached Caching

+

Multiple Memcached servers can be specified in the memcached.php +configuration file, located in the _application/config/* directory.

+

All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:

+
$this->load->driver('cache');
+$this->cache->memcached->save('foo', 'bar', 10);
+
+
+

For more information on Memcached, please see +http://php.net/memcached.

+
+
+

WinCache Caching

+

Under Windows, you can also utilize the WinCache driver.

+

All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:

+
$this->load->driver('cache');
+$this->cache->wincache->save('foo', 'bar', 10);
+
+
+

For more information on WinCache, please see +http://php.net/wincache.

+
+
+

Redis Caching

+

Redis is an in-memory key-value store which can operate in LRU cache mode. +To use it, you need Redis server and phpredis PHP extension.

+

Config options to connect to redis server must be stored in the application/config/redis.php file. +Available options are:

+
$config['socket_type'] = 'tcp'; //`tcp` or `unix`
+$config['socket'] = '/var/run/redis.sock'; // in case of `unix` socket type
+$config['host'] = '127.0.0.1';
+$config['password'] = NULL;
+$config['port'] = 6379;
+$config['timeout'] = 0;
+
+
+

All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:

+
$this->load->driver('cache');
+$this->cache->redis->save('foo', 'bar', 10);
+
+
+

For more information on Redis, please see +http://redis.io.

+
+
+

Dummy Cache

+

This is a caching backend that will always ‘miss.’ It stores no data, +but lets you keep your caching code in place in environments that don’t +support your chosen cache.

+
+
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/calendar.html b/user_guide/libraries/calendar.html new file mode 100644 index 000000000..19c5137ad --- /dev/null +++ b/user_guide/libraries/calendar.html @@ -0,0 +1,972 @@ + + + + + + + + + + Calendaring Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Calendaring Class

+

The Calendar class enables you to dynamically create calendars. Your +calendars can be formatted through the use of a calendar template, +allowing 100% control over every aspect of its design. In addition, you +can pass data to your calendar cells.

+ +
+

Using the Calendaring Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Calendar class is +initialized in your controller using the $this->load->library function:

+
$this->load->library('calendar');
+
+
+

Once loaded, the Calendar object will be available using:

+
$this->calendar
+
+
+
+
+

Displaying a Calendar

+

Here is a very simple example showing how you can display a calendar:

+
$this->load->library('calendar');
+echo $this->calendar->generate();
+
+
+

The above code will generate a calendar for the current month/year based +on your server time. To show a calendar for a specific month and year +you will pass this information to the calendar generating function:

+
$this->load->library('calendar');
+echo $this->calendar->generate(2006, 6);
+
+
+

The above code will generate a calendar showing the month of June in +2006. The first parameter specifies the year, the second parameter +specifies the month.

+
+
+

Passing Data to your Calendar Cells

+

To add data to your calendar cells involves creating an associative +array in which the keys correspond to the days you wish to populate and +the array value contains the data. The array is passed to the third +parameter of the calendar generating function. Consider this example:

+
$this->load->library('calendar');
+
+$data = array(
+        3  => 'http://example.com/news/article/2006/06/03/',
+        7  => 'http://example.com/news/article/2006/06/07/',
+        13 => 'http://example.com/news/article/2006/06/13/',
+        26 => 'http://example.com/news/article/2006/06/26/'
+);
+
+echo $this->calendar->generate(2006, 6, $data);
+
+
+

Using the above example, day numbers 3, 7, 13, and 26 will become links +pointing to the URLs you’ve provided.

+
+

Note

+

By default it is assumed that your array will contain links. +In the section that explains the calendar template below you’ll see how +you can customize how data passed to your cells is handled so you can +pass different types of information.

+
+
+
+

Setting Display Preferences

+

There are seven preferences you can set to control various aspects of +the calendar. Preferences are set by passing an array of preferences in +the second parameter of the loading function. Here is an example:

+
$prefs = array(
+        'start_day'    => 'saturday',
+        'month_type'   => 'long',
+        'day_type'     => 'short'
+);
+
+$this->load->library('calendar', $prefs);
+
+echo $this->calendar->generate();
+
+
+

The above code would start the calendar on saturday, use the “long” +month heading, and the “short” day names. More information regarding +preferences below.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefaultOptionsDescription
templateNoneNone
+
A string or array containing your calendar template.
+
See the template section below.
+
+
local_timetime()NoneA Unix timestamp corresponding to the current time.
start_daysundayAny week day (sunday, monday, tuesday, etc.)Sets the day of the week the calendar should start on.
month_typelonglong, short
+
Determines what version of the month name to use in the header.
+
long = January, short = Jan.
+
+
day_typeabrlong, short, abr
+
Determines what version of the weekday names to use in
+
the column headers. long = Sunday, short = Sun, abr = Su.
+
+
show_next_prevFALSETRUE/FALSE (boolean)
+
Determines whether to display links allowing you to toggle
+
to next/previous months. See information on this feature below.
+
+
next_prev_urlcontroller/methodA URLSets the basepath used in the next/previous calendar links.
show_other_daysFALSETRUE/FALSE (boolean)
+
Determines whether to display days of other months that share the
+
first or last week of the calendar month.
+
+
+
+ +
+

Creating a Calendar Template

+

By creating a calendar template you have 100% control over the design of +your calendar. Using the string method, each component of your calendar +will be placed within a pair of pseudo-variables as shown here:

+
$prefs['template'] = '
+
+        {table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}
+
+        {heading_row_start}<tr>{/heading_row_start}
+
+        {heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
+        {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
+        {heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}
+
+        {heading_row_end}</tr>{/heading_row_end}
+
+        {week_row_start}<tr>{/week_row_start}
+        {week_day_cell}<td>{week_day}</td>{/week_day_cell}
+        {week_row_end}</tr>{/week_row_end}
+
+        {cal_row_start}<tr>{/cal_row_start}
+        {cal_cell_start}<td>{/cal_cell_start}
+        {cal_cell_start_today}<td>{/cal_cell_start_today}
+        {cal_cell_start_other}<td class="other-month">{/cal_cell_start_other}
+
+        {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
+        {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}
+
+        {cal_cell_no_content}{day}{/cal_cell_no_content}
+        {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
+
+        {cal_cell_blank}&nbsp;{/cal_cell_blank}
+
+        {cal_cell_other}{day}{/cal_cel_other}
+
+        {cal_cell_end}</td>{/cal_cell_end}
+        {cal_cell_end_today}</td>{/cal_cell_end_today}
+        {cal_cell_end_other}</td>{/cal_cell_end_other}
+        {cal_row_end}</tr>{/cal_row_end}
+
+        {table_close}</table>{/table_close}
+';
+
+$this->load->library('calendar', $prefs);
+
+echo $this->calendar->generate();
+
+
+

Using the array method, you will pass key => value pairs. You can pass as +many or as few values as you’d like. Omitted keys will use the default values +inherited in the calendar class.

+

Example:

+
$prefs['template'] = array(
+        'table_open'           => '<table class="calendar">',
+        'cal_cell_start'       => '<td class="day">',
+        'cal_cell_start_today' => '<td class="today">'
+);
+
+$this->load->library('calendar', $prefs);
+
+echo $this->calendar->generate();
+
+
+
+
+
+

Class Reference

+
+
+class CI_Calendar
+
+
+initialize([$config = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $config (array) – Configuration parameters
  • +
+
Returns:

CI_Calendar instance (method chaining)

+
Return type:

CI_Calendar

+
+

Initializes the Calendaring preferences. Accepts an associative array as input, containing display preferences.

+
+ +
+
+generate([$year = ''[, $month = ''[, $data = array()]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $year (int) – Year
  • +
  • $month (int) – Month
  • +
  • $data (array) – Data to be shown in the calendar cells
  • +
+
Returns:

HTML-formatted calendar

+
Return type:

string

+
+

Generate the calendar.

+
+ +
+
+get_month_name($month)
+
+++ + + + + + + + +
Parameters:
    +
  • $month (int) – Month
  • +
+
Returns:

Month name

+
Return type:

string

+
+

Generates a textual month name based on the numeric month provided.

+
+ +
+
+get_day_names($day_type = '')
+
+++ + + + + + + + +
Parameters:
    +
  • $day_type (string) – ‘long’, ‘short’, or ‘abr’
  • +
+
Returns:

Array of day names

+
Return type:

array

+
+

Returns an array of day names (Sunday, Monday, etc.) based on the type +provided. Options: long, short, abr. If no $day_type is provided (or +if an invalid type is provided) this method will return the “abbreviated” +style.

+
+ +
+
+adjust_date($month, $year)
+
+++ + + + + + + + +
Parameters:
    +
  • $month (int) – Month
  • +
  • $year (int) – Year
  • +
+
Returns:

An associative array containing month and year

+
Return type:

array

+
+

This method makes sure that you have a valid month/year. For example, if +you submit 13 as the month, the year will increment and the month will +become January:

+
print_r($this->calendar->adjust_date(13, 2014));
+
+
+

outputs:

+
Array
+(
+        [month] => '01'
+        [year] => '2015'
+)
+
+
+
+ +
+
+get_total_days($month, $year)
+
+++ + + + + + + + +
Parameters:
    +
  • $month (int) – Month
  • +
  • $year (int) – Year
  • +
+
Returns:

Count of days in the specified month

+
Return type:

int

+
+

Total days in a given month:

+
echo $this->calendar->get_total_days(2, 2012);
+// 29
+
+
+
+

Note

+

This method is an alias for Date Helper function days_in_month().

+
+
+ +
+
+default_template()
+
+++ + + + + + +
Returns:An array of template values
Return type:array
+

Sets the default template. This method is used when you have not created +your own template.

+
+ +
+
+parse_template()
+
+++ + + + + + +
Returns:CI_Calendar instance (method chaining)
Return type:CI_Calendar
+

Harvests the data within the template {pseudo-variables} used to +display the calendar.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/cart.html b/user_guide/libraries/cart.html new file mode 100644 index 000000000..bb6efde35 --- /dev/null +++ b/user_guide/libraries/cart.html @@ -0,0 +1,1025 @@ + + + + + + + + + + Shopping Cart Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Shopping Cart Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Shopping Cart Class

+

The Cart Class permits items to be added to a session that stays active +while a user is browsing your site. These items can be retrieved and +displayed in a standard “shopping cart” format, allowing the user to +update the quantity or remove items from the cart.

+
+

Important

+

The Cart library is DEPRECATED and should not be used. +It is currently only kept for backwards compatibility.

+
+

Please note that the Cart Class ONLY provides the core “cart” +functionality. It does not provide shipping, credit card authorization, +or other processing components.

+ +
+

Using the Cart Class

+
+

Initializing the Shopping Cart Class

+
+

Important

+

The Cart class utilizes CodeIgniter’s Session +Class to save the cart information to a database, so +before using the Cart class you must set up a database table as +indicated in the Session Documentation, and set the +session preferences in your application/config/config.php file to +utilize a database.

+
+

To initialize the Shopping Cart Class in your controller constructor, +use the $this->load->library() method:

+
$this->load->library('cart');
+
+
+

Once loaded, the Cart object will be available using:

+
$this->cart
+
+
+
+

Note

+

The Cart Class will load and initialize the Session Class +automatically, so unless you are using sessions elsewhere in your +application, you do not need to load the Session class.

+
+
+
+

Adding an Item to The Cart

+

To add an item to the shopping cart, simply pass an array with the +product information to the $this->cart->insert() method, as shown +below:

+
$data = array(
+        'id'      => 'sku_123ABC',
+        'qty'     => 1,
+        'price'   => 39.95,
+        'name'    => 'T-Shirt',
+        'options' => array('Size' => 'L', 'Color' => 'Red')
+);
+
+$this->cart->insert($data);
+
+
+
+

Important

+

The first four array indexes above (id, qty, price, and +name) are required. If you omit any of them the data will not be +saved to the cart. The fifth index (options) is optional. It is intended +to be used in cases where your product has options associated with it. +Use an array for options, as shown above.

+
+

The five reserved indexes are:

+
    +
  • id - Each product in your store must have a unique identifier. +Typically this will be an “sku” or other such identifier.
  • +
  • qty - The quantity being purchased.
  • +
  • price - The price of the item.
  • +
  • name - The name of the item.
  • +
  • options - Any additional attributes that are needed to identify +the product. These must be passed via an array.
  • +
+

In addition to the five indexes above, there are two reserved words: +rowid and subtotal. These are used internally by the Cart class, so +please do NOT use those words as index names when inserting data into +the cart.

+

Your array may contain additional data. Anything you include in your +array will be stored in the session. However, it is best to standardize +your data among all your products in order to make displaying the +information in a table easier.

+
$data = array(
+        'id'      => 'sku_123ABC',
+        'qty'     => 1,
+        'price'   => 39.95,
+        'name'    => 'T-Shirt',
+        'coupon'         => 'XMAS-50OFF'
+);
+
+$this->cart->insert($data);
+
+
+

The insert() method will return the $rowid if you successfully insert a +single item.

+
+
+

Adding Multiple Items to The Cart

+

By using a multi-dimensional array, as shown below, it is possible to +add multiple products to the cart in one action. This is useful in cases +where you wish to allow people to select from among several items on the +same page.

+
$data = array(
+        array(
+                'id'      => 'sku_123ABC',
+                'qty'     => 1,
+                'price'   => 39.95,
+                'name'    => 'T-Shirt',
+                'options' => array('Size' => 'L', 'Color' => 'Red')
+        ),
+        array(
+                'id'      => 'sku_567ZYX',
+                'qty'     => 1,
+                'price'   => 9.95,
+                'name'    => 'Coffee Mug'
+        ),
+        array(
+                'id'      => 'sku_965QRS',
+                'qty'     => 1,
+                'price'   => 29.95,
+                'name'    => 'Shot Glass'
+        )
+);
+
+$this->cart->insert($data);
+
+
+
+
+

Displaying the Cart

+

To display the cart you will create a view +file with code similar to the one shown below.

+

Please note that this example uses the form +helper.

+
<?php echo form_open('path/to/controller/update/method'); ?>
+
+<table cellpadding="6" cellspacing="1" style="width:100%" border="0">
+
+<tr>
+        <th>QTY</th>
+        <th>Item Description</th>
+        <th style="text-align:right">Item Price</th>
+        <th style="text-align:right">Sub-Total</th>
+</tr>
+
+<?php $i = 1; ?>
+
+<?php foreach ($this->cart->contents() as $items): ?>
+
+        <?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>
+
+        <tr>
+                <td><?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td>
+                <td>
+                        <?php echo $items['name']; ?>
+
+                        <?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>
+
+                                <p>
+                                        <?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
+
+                                                <strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />
+
+                                        <?php endforeach; ?>
+                                </p>
+
+                        <?php endif; ?>
+
+                </td>
+                <td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
+                <td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
+        </tr>
+
+<?php $i++; ?>
+
+<?php endforeach; ?>
+
+<tr>
+        <td colspan="2"> </td>
+        <td class="right"><strong>Total</strong></td>
+        <td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
+</tr>
+
+</table>
+
+<p><?php echo form_submit('', 'Update your Cart'); ?></p>
+
+
+
+
+

Updating The Cart

+

To update the information in your cart, you must pass an array +containing the Row ID and one or more pre-defined properties to the +$this->cart->update() method.

+
+

Note

+

If the quantity is set to zero, the item will be removed from +the cart.

+
+
$data = array(
+        'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
+        'qty'   => 3
+);
+
+$this->cart->update($data);
+
+// Or a multi-dimensional array
+
+$data = array(
+        array(
+                'rowid'   => 'b99ccdf16028f015540f341130b6d8ec',
+                'qty'     => 3
+        ),
+        array(
+                'rowid'   => 'xw82g9q3r495893iajdh473990rikw23',
+                'qty'     => 4
+        ),
+        array(
+                'rowid'   => 'fh4kdkkkaoe30njgoe92rkdkkobec333',
+                'qty'     => 2
+        )
+);
+
+$this->cart->update($data);
+
+
+

You may also update any property you have previously defined when +inserting the item such as options, price or other custom fields.

+
$data = array(
+        'rowid'  => 'b99ccdf16028f015540f341130b6d8ec',
+        'qty'    => 1,
+        'price'  => 49.95,
+        'coupon' => NULL
+);
+
+$this->cart->update($data);
+
+
+
+

What is a Row ID?

+

The row ID is a unique identifier that is generated by the cart code +when an item is added to the cart. The reason a unique ID is created +is so that identical products with different options can be managed +by the cart.

+

For example, let’s say someone buys two identical t-shirts (same product +ID), but in different sizes. The product ID (and other attributes) will +be identical for both sizes because it’s the same shirt. The only +difference will be the size. The cart must therefore have a means of +identifying this difference so that the two sizes of shirts can be +managed independently. It does so by creating a unique “row ID” based on +the product ID and any options associated with it.

+

In nearly all cases, updating the cart will be something the user does +via the “view cart” page, so as a developer, it is unlikely that you +will ever have to concern yourself with the “row ID”, other than making +sure your “view cart” page contains this information in a hidden form +field, and making sure it gets passed to the update() method when +the update form is submitted. Please examine the construction of the +“view cart” page above for more information.

+
+
+
+
+

Class Reference

+
+
+class CI_Cart
+
+
+$product_id_rules = '.a-z0-9_-'
+

These are the regular expression rules that we use to validate the product +ID - alpha-numeric, dashes, underscores, or periods by default

+
+ +
+
+$product_name_rules = 'w -.:'
+

These are the regular expression rules that we use to validate the product ID and product name - alpha-numeric, dashes, underscores, colons or periods by +default

+
+ +
+
+$product_name_safe = TRUE
+

Whether or not to only allow safe product names. Default TRUE.

+
+ +
+
+insert([$items = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $items (array) – Items to insert into the cart
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Insert items into the cart and save it to the session table. Returns TRUE +on success and FALSE on failure.

+
+ +
+
+update([$items = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $items (array) – Items to update in the cart
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

This method permits changing the properties of a given item. +Typically it is called from the “view cart” page if a user makes changes +to the quantity before checkout. That array must contain the rowid +for each item.

+
+ +
+
+remove($rowid)
+
+++ + + + + + + + +
Parameters:
    +
  • $rowid (int) – ID of the item to remove from the cart
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Allows you to remove an item from the shopping cart by passing it the +$rowid.

+
+ +
+
+total()
+
+++ + + + + + +
Returns:Total amount
Return type:int
+

Displays the total amount in the cart.

+
+ +
+
+total_items()
+
+++ + + + + + +
Returns:Total amount of items in the cart
Return type:int
+

Displays the total number of items in the cart.

+
+ +
+
+contents([$newest_first = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $newest_first (bool) – Whether to order the array with newest items first
  • +
+
Returns:

An array of cart contents

+
Return type:

array

+
+

Returns an array containing everything in the cart. You can sort the +order by which the array is returned by passing it TRUE where the contents +will be sorted from newest to oldest, otherwise it is sorted from oldest +to newest.

+
+ +
+
+get_item($row_id)
+
+++ + + + + + + + +
Parameters:
    +
  • $row_id (int) – Row ID to retrieve
  • +
+
Returns:

Array of item data

+
Return type:

array

+
+

Returns an array containing data for the item matching the specified row +ID, or FALSE if no such item exists.

+
+ +
+
+has_options($row_id = '')
+
+++ + + + + + + + +
Parameters:
    +
  • $row_id (int) – Row ID to inspect
  • +
+
Returns:

TRUE if options exist, FALSE otherwise

+
Return type:

bool

+
+

Returns TRUE (boolean) if a particular row in the cart contains options. +This method is designed to be used in a loop with contents(), since +you must pass the rowid to this method, as shown in the Displaying +the Cart example above.

+
+ +
+
+product_options([$row_id = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $row_id (int) – Row ID
  • +
+
Returns:

Array of product options

+
Return type:

array

+
+

Returns an array of options for a particular product. This method is +designed to be used in a loop with contents(), since you +must pass the rowid to this method, as shown in the Displaying the +Cart example above.

+
+ +
+
+destroy()
+
+++ + + + +
Return type:void
+

Permits you to destroy the cart. This method will likely be called +when you are finished processing the customer’s order.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/config.html b/user_guide/libraries/config.html new file mode 100644 index 000000000..7052c79e0 --- /dev/null +++ b/user_guide/libraries/config.html @@ -0,0 +1,834 @@ + + + + + + + + + + Config Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Config Class

+

The Config class provides a means to retrieve configuration preferences. +These preferences can come from the default config file +(application/config/config.php) or from your own custom config files.

+
+

Note

+

This class is initialized automatically by the system so there +is no need to do it manually.

+
+ +
+

Working with the Config Class

+
+

Anatomy of a Config File

+

By default, CodeIgniter has one primary config file, located at +application/config/config.php. If you open the file using your text +editor you’ll see that config items are stored in an array called +$config.

+

You can add your own config items to this file, or if you prefer to keep +your configuration items separate (assuming you even need config items), +simply create your own file and save it in config folder.

+
+

Note

+

If you do create your own config files use the same format as +the primary one, storing your items in an array called $config. +CodeIgniter will intelligently manage these files so there will be no +conflict even though the array has the same name (assuming an array +index is not named the same as another).

+
+
+
+

Loading a Config File

+
+

Note

+

CodeIgniter automatically loads the primary config file +(application/config/config.php), so you will only need to load a config +file if you have created your own.

+
+

There are two ways to load a config file:

+
+

Manual Loading

+

To load one of your custom config files you will use the following +function within the controller that +needs it:

+
$this->config->load('filename');
+
+
+

Where filename is the name of your config file, without the .php file +extension.

+

If you need to load multiple config files normally they will be +merged into one master config array. Name collisions can occur, +however, if you have identically named array indexes in different +config files. To avoid collisions you can set the second parameter to +TRUE and each config file will be stored in an array index +corresponding to the name of the config file. Example:

+
// Stored in an array with this prototype: $this->config['blog_settings'] = $config
+$this->config->load('blog_settings', TRUE);
+
+
+

Please see the section entitled Fetching Config Items below to learn +how to retrieve config items set this way.

+

The third parameter allows you to suppress errors in the event that a +config file does not exist:

+
$this->config->load('blog_settings', FALSE, TRUE);
+
+
+
+
+

Auto-loading

+

If you find that you need a particular config file globally, you can +have it loaded automatically by the system. To do this, open the +autoload.php file, located at application/config/autoload.php, +and add your config file as indicated in the file.

+
+
+
+

Fetching Config Items

+

To retrieve an item from your config file, use the following function:

+
$this->config->item('item_name');
+
+
+

Where item_name is the $config array index you want to retrieve. For +example, to fetch your language choice you’ll do this:

+
$lang = $this->config->item('language');
+
+
+

The function returns NULL if the item you are trying to fetch +does not exist.

+

If you are using the second parameter of the $this->config->load +function in order to assign your config items to a specific index you +can retrieve it by specifying the index name in the second parameter of +the $this->config->item() function. Example:

+
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
+$this->config->load('blog_settings', TRUE);
+
+// Retrieve a config item named site_name contained within the blog_settings array
+$site_name = $this->config->item('site_name', 'blog_settings');
+
+// An alternate way to specify the same item:
+$blog_config = $this->config->item('blog_settings');
+$site_name = $blog_config['site_name'];
+
+
+
+
+

Setting a Config Item

+

If you would like to dynamically set a config item or change an existing +one, you can do so using:

+
$this->config->set_item('item_name', 'item_value');
+
+
+

Where item_name is the $config array index you want to change, and +item_value is its value.

+
+
+

Environments

+

You may load different configuration files depending on the current +environment. The ENVIRONMENT constant is defined in index.php, and is +described in detail in the Handling +Environments section.

+

To create an environment-specific configuration file, create or copy a +configuration file in application/config/{ENVIRONMENT}/{FILENAME}.php

+

For example, to create a production-only config.php, you would:

+
    +
  1. Create the directory application/config/production/
  2. +
  3. Copy your existing config.php into the above directory
  4. +
  5. Edit application/config/production/config.php so it contains your +production settings
  6. +
+

When you set the ENVIRONMENT constant to ‘production’, the settings for +your new production-only config.php will be loaded.

+

You can place the following configuration files in environment-specific +folders:

+
    +
  • Default CodeIgniter configuration files
  • +
  • Your own custom configuration files
  • +
+
+

Note

+

CodeIgniter always loads the global config file first (i.e., the one in application/config/), +then tries to load the configuration files for the current environment. +This means you are not obligated to place all of your configuration files in an +environment folder. Only the files that change per environment. Additionally you don’t +have to copy all the config items in the environment config file. Only the config items +that you wish to change for your environment. The config items declared in your environment +folders always overwrite those in your global config files.

+
+
+
+
+

Class Reference

+
+
+class CI_Config
+
+
+$config
+

Array of all loaded config values

+
+ +
+
+$is_loaded
+

Array of all loaded config files

+
+ +
+
+item($item[, $index=''])
+
+++ + + + + + + + +
Parameters:
    +
  • $item (string) – Config item name
  • +
  • $index (string) – Index name
  • +
+
Returns:

Config item value or NULL if not found

+
Return type:

mixed

+
+

Fetch a config file item.

+
+ +
+
+set_item($item, $value)
+
+++ + + + + + +
Parameters:
    +
  • $item (string) – Config item name
  • +
  • $value (string) – Config item value
  • +
+
Return type:

void

+
+

Sets a config file item to the specified value.

+
+ +
+
+slash_item($item)
+
+++ + + + + + + + +
Parameters:
    +
  • $item (string) – config item name
  • +
+
Returns:

Config item value with a trailing forward slash or NULL if not found

+
Return type:

mixed

+
+

This method is identical to item(), except it appends a forward +slash to the end of the item, if it exists.

+
+ +
+
+load([$file = ''[, $use_sections = FALSE[, $fail_gracefully = FALSE]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $file (string) – Configuration file name
  • +
  • $use_sections (bool) – Whether config values should be loaded into their own section (index of the main config array)
  • +
  • $fail_gracefully (bool) – Whether to return FALSE or to display an error message
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Loads a configuration file.

+
+ +
+
+site_url()
+
+++ + + + + + +
Returns:Site URL
Return type:string
+

This method retrieves the URL to your site, along with the “index” value +you’ve specified in the config file.

+

This method is normally accessed via the corresponding functions in the +URL Helper.

+
+ +
+
+base_url()
+
+++ + + + + + +
Returns:Base URL
Return type:string
+

This method retrieves the URL to your site, plus an optional path such +as to a stylesheet or image.

+

This method is normally accessed via the corresponding functions in the +URL Helper.

+
+ +
+
+system_url()
+
+++ + + + + + +
Returns:URL pointing at your CI system/ directory
Return type:string
+

This method retrieves the URL to your CodeIgniter system/ directory.

+
+

Note

+

This method is DEPRECATED because it encourages usage of +insecure coding practices. Your system/ directory shouldn’t +be publicly accessible.

+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/email.html b/user_guide/libraries/email.html new file mode 100644 index 000000000..34c7440b3 --- /dev/null +++ b/user_guide/libraries/email.html @@ -0,0 +1,1218 @@ + + + + + + + + + + Email Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Email Class

+

CodeIgniter’s robust Email Class supports the following features:

+
    +
  • Multiple Protocols: Mail, Sendmail, and SMTP
  • +
  • TLS and SSL Encryption for SMTP
  • +
  • Multiple recipients
  • +
  • CC and BCCs
  • +
  • HTML or Plaintext email
  • +
  • Attachments
  • +
  • Word wrapping
  • +
  • Priorities
  • +
  • BCC Batch Mode, enabling large email lists to be broken into small +BCC batches.
  • +
  • Email Debugging tools
  • +
+ +
+

Using the Email Library

+
+

Sending Email

+

Sending email is not only simple, but you can configure it on the fly or +set your preferences in a config file.

+

Here is a basic example demonstrating how you might send email. Note: +This example assumes you are sending the email from one of your +controllers.

+
$this->load->library('email');
+
+$this->email->from('your@example.com', 'Your Name');
+$this->email->to('someone@example.com');
+$this->email->cc('another@another-example.com');
+$this->email->bcc('them@their-example.com');
+
+$this->email->subject('Email Test');
+$this->email->message('Testing the email class.');
+
+$this->email->send();
+
+
+
+
+

Setting Email Preferences

+

There are 21 different preferences available to tailor how your email +messages are sent. You can either set them manually as described here, +or automatically via preferences stored in your config file, described +below:

+

Preferences are set by passing an array of preference values to the +email initialize method. Here is an example of how you might set some +preferences:

+
$config['protocol'] = 'sendmail';
+$config['mailpath'] = '/usr/sbin/sendmail';
+$config['charset'] = 'iso-8859-1';
+$config['wordwrap'] = TRUE;
+
+$this->email->initialize($config);
+
+
+
+

Note

+

Most of the preferences have default values that will be used +if you do not set them.

+
+
+

Setting Email Preferences in a Config File

+

If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called the +email.php, add the $config array in that file. Then save the file at +config/email.php and it will be used automatically. You will NOT need to +use the $this->email->initialize() method if you save your +preferences in a config file.

+
+
+
+

Email Preferences

+

The following is a list of all the preferences that can be set when +sending email.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
useragentCodeIgniterNoneThe “user agent”.
protocolmailmail, sendmail, or smtpThe mail sending protocol.
mailpath/usr/sbin/sendmailNoneThe server path to Sendmail.
smtp_hostNo DefaultNoneSMTP Server Address.
smtp_userNo DefaultNoneSMTP Username.
smtp_passNo DefaultNoneSMTP Password.
smtp_port25NoneSMTP Port.
smtp_timeout5NoneSMTP Timeout (in seconds).
smtp_keepaliveFALSETRUE or FALSE (boolean)Enable persistent SMTP connections.
smtp_cryptoNo Defaulttls or sslSMTP Encryption
wordwrapTRUETRUE or FALSE (boolean)Enable word-wrap.
wrapchars76 Character count to wrap at.
mailtypetexttext or htmlType of mail. If you send HTML email you must send it as a complete web +page. Make sure you don’t have any relative links or relative image +paths otherwise they will not work.
charset$config['charset'] Character set (utf-8, iso-8859-1, etc.).
validateFALSETRUE or FALSE (boolean)Whether to validate the email address.
priority31, 2, 3, 4, 5Email Priority. 1 = highest. 5 = lowest. 3 = normal.
crlf\n“\r\n” or “\n” or “\r”Newline character. (Use “\r\n” to comply with RFC 822).
newline\n“\r\n” or “\n” or “\r”Newline character. (Use “\r\n” to comply with RFC 822).
bcc_batch_modeFALSETRUE or FALSE (boolean)Enable BCC Batch Mode.
bcc_batch_size200NoneNumber of emails in each BCC batch.
dsnFALSETRUE or FALSE (boolean)Enable notify message from server
+
+
+

Overriding Word Wrapping

+

If you have word wrapping enabled (recommended to comply with RFC 822) +and you have a very long link in your email it can get wrapped too, +causing it to become un-clickable by the person receiving it. +CodeIgniter lets you manually override word wrapping within part of your +message like this:

+
The text of your email that
+gets wrapped normally.
+
+{unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}
+
+More text that will be
+wrapped normally.
+
+
+

Place the item you do not want word-wrapped between: {unwrap} {/unwrap}

+
+
+
+

Class Reference

+
+
+class CI_Email
+
+
+from($from[, $name = ''[, $return_path = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $from (string) – “From” e-mail address
  • +
  • $name (string) – “From” display name
  • +
  • $return_path (string) – Optional email address to redirect undelivered e-mail to
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the email address and name of the person sending the email:

+
$this->email->from('you@example.com', 'Your Name');
+
+
+

You can also set a Return-Path, to help redirect undelivered mail:

+
$this->email->from('you@example.com', 'Your Name', 'returned_emails@example.com');
+
+
+
+

Note

+

Return-Path can’t be used if you’ve configured ‘smtp’ as +your protocol.

+
+
+ +
+
+reply_to($replyto[, $name = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $replyto (string) – E-mail address for replies
  • +
  • $name (string) – Display name for the reply-to e-mail address
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the reply-to address. If the information is not provided the +information in the :meth:from method is used. Example:

+
$this->email->reply_to('you@example.com', 'Your Name');
+
+
+
+ +
+
+to($to)
+
+++ + + + + + + + +
Parameters:
    +
  • $to (mixed) – Comma-delimited string or an array of e-mail addresses
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the email address(s) of the recipient(s). Can be a single e-mail, +a comma-delimited list or an array:

+
$this->email->to('someone@example.com');
+
+
+
$this->email->to('one@example.com, two@example.com, three@example.com');
+
+
+
$this->email->to(
+        array('one@example.com', 'two@example.com', 'three@example.com')
+);
+
+
+
+ +
+
+cc($cc)
+
+++ + + + + + + + +
Parameters:
    +
  • $cc (mixed) – Comma-delimited string or an array of e-mail addresses
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the CC email address(s). Just like the “to”, can be a single e-mail, +a comma-delimited list or an array.

+
+ +
+
+bcc($bcc[, $limit = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $bcc (mixed) – Comma-delimited string or an array of e-mail addresses
  • +
  • $limit (int) – Maximum number of e-mails to send per batch
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the BCC email address(s). Just like the to() method, can be a single +e-mail, a comma-delimited list or an array.

+

If $limit is set, “batch mode” will be enabled, which will send +the emails to batches, with each batch not exceeding the specified +$limit.

+
+ +
+
+subject($subject)
+
+++ + + + + + + + +
Parameters:
    +
  • $subject (string) – E-mail subject line
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the email subject:

+
$this->email->subject('This is my subject');
+
+
+
+ +
+
+message($body)
+
+++ + + + + + + + +
Parameters:
    +
  • $body (string) – E-mail message body
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the e-mail message body:

+
$this->email->message('This is my message');
+
+
+
+ +
+
+set_alt_message($str)
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Alternative e-mail message body
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Sets the alternative e-mail message body:

+
$this->email->set_alt_message('This is the alternative message');
+
+
+

This is an optional message string which can be used if you send +HTML formatted email. It lets you specify an alternative message +with no HTML formatting which is added to the header string for +people who do not accept HTML email. If you do not set your own +message CodeIgniter will extract the message from your HTML email +and strip the tags.

+
+ +
+
+set_header($header, $value)
+
+++ + + + + + + + +
Parameters:
    +
  • $header (string) – Header name
  • +
  • $value (string) – Header value
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Appends additional headers to the e-mail:

+
$this->email->set_header('Header1', 'Value1');
+$this->email->set_header('Header2', 'Value2');
+
+
+
+ +
+
+clear([$clear_attachments = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $clear_attachments (bool) – Whether or not to clear attachments
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Initializes all the email variables to an empty state. This method +is intended for use if you run the email sending method in a loop, +permitting the data to be reset between cycles.

+
foreach ($list as $name => $address)
+{
+        $this->email->clear();
+
+        $this->email->to($address);
+        $this->email->from('your@example.com');
+        $this->email->subject('Here is your info '.$name);
+        $this->email->message('Hi '.$name.' Here is the info you requested.');
+        $this->email->send();
+}
+
+
+

If you set the parameter to TRUE any attachments will be cleared as +well:

+
$this->email->clear(TRUE);
+
+
+
+ +
+
+send([$auto_clear = TRUE])
+
+++ + + + + + + + +
Parameters:
    +
  • $auto_clear (bool) – Whether to clear message data automatically
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

The e-mail sending method. Returns boolean TRUE or FALSE based on +success or failure, enabling it to be used conditionally:

+
if ( ! $this->email->send())
+{
+        // Generate error
+}
+
+
+

This method will automatically clear all parameters if the request was +successful. To stop this behaviour pass FALSE:

+
if ($this->email->send(FALSE))
+{
+        // Parameters won't be cleared
+}
+
+
+
+

Note

+

In order to use the print_debugger() method, you need +to avoid clearing the email parameters.

+
+
+ +
+
+attach($filename[, $disposition = ''[, $newname = NULL[, $mime = '']]])
+
+++ + + + + + + + +
Parameters:
    +
  • $filename (string) – File name
  • +
  • $disposition (string) – ‘disposition’ of the attachment. Most +email clients make their own decision regardless of the MIME +specification used here. https://www.iana.org/assignments/cont-disp/cont-disp.xhtml
  • +
  • $newname (string) – Custom file name to use in the e-mail
  • +
  • $mime (string) – MIME type to use (useful for buffered data)
  • +
+
Returns:

CI_Email instance (method chaining)

+
Return type:

CI_Email

+
+

Enables you to send an attachment. Put the file path/name in the first +parameter. For multiple attachments use the method multiple times. +For example:

+
$this->email->attach('/path/to/photo1.jpg');
+$this->email->attach('/path/to/photo2.jpg');
+$this->email->attach('/path/to/photo3.jpg');
+
+
+

To use the default disposition (attachment), leave the second parameter blank, +otherwise use a custom disposition:

+
$this->email->attach('image.jpg', 'inline');
+
+
+

You can also use a URL:

+
$this->email->attach('http://example.com/filename.pdf');
+
+
+

If you’d like to use a custom file name, you can use the third parameter:

+
$this->email->attach('filename.pdf', 'attachment', 'report.pdf');
+
+
+

If you need to use a buffer string instead of a real - physical - file you can +use the first parameter as buffer, the third parameter as file name and the fourth +parameter as mime-type:

+
$this->email->attach($buffer, 'attachment', 'report.pdf', 'application/pdf');
+
+
+
+ +
+
+attachment_cid($filename)
+
+++ + + + + + + + +
Parameters:
    +
  • $filename (string) – Existing attachment filename
  • +
+
Returns:

Attachment Content-ID or FALSE if not found

+
Return type:

string

+
+

Sets and returns an attachment’s Content-ID, which enables your to embed an inline +(picture) attachment into HTML. First parameter must be the already attached file name.

+
$filename = '/img/photo1.jpg';
+$this->email->attach($filename);
+foreach ($list as $address)
+{
+        $this->email->to($address);
+        $cid = $this->email->attachment_cid($filename);
+        $this->email->message('<img src="cid:'. $cid .'" alt="photo1" />');
+        $this->email->send();
+}
+
+
+
+

Note

+

Content-ID for each e-mail must be re-created for it to be unique.

+
+
+ +
+
+print_debugger([$include = array('headers', 'subject', 'body')])
+
+++ + + + + + + + +
Parameters:
    +
  • $include (array) – Which parts of the message to print out
  • +
+
Returns:

Formatted debug data

+
Return type:

string

+
+

Returns a string containing any server messages, the email headers, and +the email message. Useful for debugging.

+

You can optionally specify which parts of the message should be printed. +Valid options are: headers, subject, body.

+

Example:

+
// You need to pass FALSE while sending in order for the email data
+// to not be cleared - if that happens, print_debugger() would have
+// nothing to output.
+$this->email->send(FALSE);
+
+// Will only print the email headers, excluding the message subject and body
+$this->email->print_debugger(array('headers'));
+
+
+
+

Note

+

By default, all of the raw data will be printed.

+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/encrypt.html b/user_guide/libraries/encrypt.html new file mode 100644 index 000000000..edbb41041 --- /dev/null +++ b/user_guide/libraries/encrypt.html @@ -0,0 +1,787 @@ + + + + + + + + + + Encrypt Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Encrypt Class

+

The Encrypt Class provides two-way data encryption. It encrypted using +the Mcrypt PHP extension, which is required for the Encrypt Class to run.

+
+

Important

+

This library has been DEPRECATED and is only kept for +backwards compatibility. Please use the new Encryption Library.

+
+ +
+

Using the Encrypt Library

+
+

Setting your Key

+

A key is a piece of information that controls the cryptographic +process and permits an encrypted string to be decoded. In fact, the key +you chose will provide the only means to decode data that was +encrypted with that key, so not only must you choose the key carefully, +you must never change it if you intend use it for persistent data.

+

It goes without saying that you should guard your key carefully. Should +someone gain access to your key, the data will be easily decoded. If +your server is not totally under your control it’s impossible to ensure +key security so you may want to think carefully before using it for +anything that requires high security, like storing credit card numbers.

+

To take maximum advantage of the encryption algorithm, your key should +be 32 characters in length (256 bits). The key should be as random a +string as you can concoct, with numbers and uppercase and lowercase +letters. Your key should not be a simple text string. In order to be +cryptographically secure it needs to be as random as possible.

+

Your key can be either stored in your application/config/config.php, or +you can design your own storage mechanism and pass the key dynamically +when encoding/decoding.

+

To save your key to your application/config/config.php, open the file +and set:

+
$config['encryption_key'] = "YOUR KEY";
+
+
+
+
+

Message Length

+

It’s important for you to know that the encoded messages the encryption +function generates will be approximately 2.6 times longer than the +original message. For example, if you encrypt the string “my super +secret data”, which is 21 characters in length, you’ll end up with an +encoded string that is roughly 55 characters (we say “roughly” because +the encoded string length increments in 64 bit clusters, so it’s not +exactly linear). Keep this information in mind when selecting your data +storage mechanism. Cookies, for example, can only hold 4K of +information.

+
+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Encrypt class is +initialized in your controller using the $this->load->library() +method:

+
$this->load->library('encrypt');
+
+
+

Once loaded, the Encrypt library object will be available using:

+
$this->encrypt
+
+
+
+
+
+

Class Reference

+
+
+class CI_Encrypt
+
+
+encode($string[, $key = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $string (string) – Data to encrypt
  • +
  • $key (string) – Encryption key
  • +
+
Returns:

Encrypted string

+
Return type:

string

+
+

Performs the data encryption and returns it as a string. Example:

+
$msg = 'My secret message';
+
+$encrypted_string = $this->encrypt->encode($msg);
+
+
+

You can optionally pass your encryption key via the second parameter if +you don’t want to use the one in your config file:

+
$msg = 'My secret message';
+$key = 'super-secret-key';
+
+$encrypted_string = $this->encrypt->encode($msg, $key);
+
+
+
+ +
+
+decode($string[, $key = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $string (string) – String to decrypt
  • +
  • $key (string) – Encryption key
  • +
+
Returns:

Plain-text string

+
Return type:

string

+
+

Decrypts an encoded string. Example:

+
$encrypted_string = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84';
+
+$plaintext_string = $this->encrypt->decode($encrypted_string);
+
+
+

You can optionally pass your encryption key via the second parameter if +you don’t want to use the one in your config file:

+
$msg = 'My secret message';
+$key = 'super-secret-key';
+
+$encrypted_string = $this->encrypt->decode($msg, $key);
+
+
+
+ +
+
+set_cipher($cipher)
+
+++ + + + + + + + +
Parameters:
    +
  • $cipher (int) – Valid PHP MCrypt cypher constant
  • +
+
Returns:

CI_Encrypt instance (method chaining)

+
Return type:

CI_Encrypt

+
+

Permits you to set an Mcrypt cipher. By default it uses +MCRYPT_RIJNDAEL_256. Example:

+
$this->encrypt->set_cipher(MCRYPT_BLOWFISH);
+
+
+

Please visit php.net for a list of available ciphers.

+

If you’d like to manually test whether your server supports MCrypt you +can use:

+
echo extension_loaded('mcrypt') ? 'Yup' : 'Nope';
+
+
+
+ +
+
+set_mode($mode)
+
+++ + + + + + + + +
Parameters:
    +
  • $mode (int) – Valid PHP MCrypt mode constant
  • +
+
Returns:

CI_Encrypt instance (method chaining)

+
Return type:

CI_Encrypt

+
+

Permits you to set an Mcrypt mode. By default it uses MCRYPT_MODE_CBC. +Example:

+
$this->encrypt->set_mode(MCRYPT_MODE_CFB);
+
+
+

Please visit php.net for a list of available modes.

+
+ +
+
+encode_from_legacy($string[, $legacy_mode = MCRYPT_MODE_ECB[, $key = '']])
+
+++ + + + + + + + +
Parameters:
    +
  • $string (string) – String to encrypt
  • +
  • $legacy_mode (int) – Valid PHP MCrypt cipher constant
  • +
  • $key (string) – Encryption key
  • +
+
Returns:

Newly encrypted string

+
Return type:

string

+
+

Enables you to re-encode data that was originally encrypted with +CodeIgniter 1.x to be compatible with the Encrypt library in +CodeIgniter 2.x. It is only necessary to use this method if you have +encrypted data stored permanently such as in a file or database and are +on a server that supports Mcrypt. “Light” use encryption such as +encrypted session data or transitory encrypted flashdata require no +intervention on your part. However, existing encrypted Sessions will be +destroyed since data encrypted prior to 2.x will not be decoded.

+
+

Important

+

Why only a method to re-encode the data instead of maintaining legacy +methods for both encoding and decoding? The algorithms in the +Encrypt library have improved in CodeIgniter 2.x both for performance +and security, and we do not wish to encourage continued use of the older +methods. You can of course extend the Encryption library if you wish and +replace the new methods with the old and retain seamless compatibility +with CodeIgniter 1.x encrypted data, but this a decision that a +developer should make cautiously and deliberately, if at all.

+
+
$new_data = $this->encrypt->encode_from_legacy($old_encrypted_string);
+
+
+ +++++ + + + + + + + + + + + + + + + + + + + + +
ParameterDefaultDescription
$orig_datan/aThe original encrypted data from CodeIgniter 1.x’s Encryption library
$legacy_modeMCRYPT_MODE_ECBThe Mcrypt mode that was used to generate the original encrypted data. +CodeIgniter 1.x’s default was MCRYPT_MODE_ECB, and it will assume that +to be the case unless overridden by this parameter.
$keyn/aThe encryption key. This it typically specified in your config file as +outlined above.
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/encryption.html b/user_guide/libraries/encryption.html new file mode 100644 index 000000000..4904c496b --- /dev/null +++ b/user_guide/libraries/encryption.html @@ -0,0 +1,1405 @@ + + + + + + + + + + Encryption Library — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Encryption Library
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Encryption Library

+
+

Important

+

DO NOT use this or any other encryption library for +user password storage! Passwords must be hashed instead, and you +should do that via PHP’s own Password Hashing extension.

+
+

The Encryption Library provides two-way data encryption. To do so in +a cryptographically secure way, it utilizes PHP extensions that are +unfortunately not always available on all systems. +You must meet one of the following dependencies in order to use this +library:

+ +

If neither of the above dependencies is met, we simply cannot offer +you a good enough implementation to meet the high standards required +for proper cryptography.

+ +
+

Using the Encryption Library

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Encryption library is +initialized in your controller using the $this->load->library() +method:

+
$this->load->library('encryption');
+
+
+

Once loaded, the Encryption library object will be available using:

+
$this->encryption
+
+
+
+
+

Default behavior

+

By default, the Encryption Library will use the AES-128 cipher in CBC +mode, using your configured encryption_key and SHA512 HMAC authentication.

+
+

Note

+

AES-128 is chosen both because it is proven to be strong and +because of its wide availability across different cryptographic +software and programming languages’ APIs.

+
+

However, the encryption_key is not used as is.

+

If you are somewhat familiar with cryptography, you should already know +that a HMAC also requires a secret key and using the same key for both +encryption and authentication is a bad practice.

+

Because of that, two separate keys are derived from your already configured +encryption_key: one for encryption and one for authentication. This is +done via a technique called HMAC-based Key Derivation Function (HKDF).

+
+
+

Setting your encryption_key

+

An encryption key is a piece of information that controls the +cryptographic process and permits a plain-text string to be encrypted, +and afterwards - decrypted. It is the secret “ingredient” in the whole +process that allows you to be the only one who is able to decrypt data +that you’ve decided to hide from the eyes of the public. +After one key is used to encrypt data, that same key provides the only +means to decrypt it, so not only must you chose one carefully, but you +must not lose it or you will also lose access to the data.

+

It must be noted that to ensure maximum security, such key should not +only be as strong as possible, but also often changed. Such behavior +however is rarely practical or possible to implement, and that is why +CodeIgniter gives you the ability to configure a single key that is to be +used (almost) every time.

+

It goes without saying that you should guard your key carefully. Should +someone gain access to your key, the data will be easily decrypted. If +your server is not totally under your control it’s impossible to ensure +key security so you may want to think carefully before using it for +anything that requires high security, like storing credit card numbers.

+

Your encryption key must be as long as the encyption algorithm in use +allows. For AES-128, that’s 128 bits or 16 bytes (charcters) long. +You will find a table below that shows the supported key lengths of +different ciphers.

+

The key should be as random as possible and it must not be a regular +text string, nor the output of a hashing function, etc. In order to create +a proper key, you must use the Encryption library’s create_key() method

+
// $key will be assigned a 16-byte (128-bit) random key
+$key = $this->encryption->create_key(16);
+
+
+

The key can be either stored in your application/config/config.php, or +you can design your own storage mechanism and pass the key dynamically +when encrypting/decrypting.

+

To save your key to your application/config/config.php, open the file +and set:

+
$config['encryption_key'] = 'YOUR KEY';
+
+
+

You’ll notice that the create_key() method outputs binary data, which +is hard to deal with (i.e. a copy-paste may damage it), so you may use +bin2hex(), hex2bin() or Base64-encoding to work with the key in +a more friendly manner. For example:

+
// Get a hex-encoded representation of the key:
+$key = bin2hex($this->encryption->create_key(16));
+
+// Put the same value in your config with hex2bin(),
+// so that it is still passed as binary to the library:
+$config['encryption_key'] = hex2bin(<your hex-encoded key>);
+
+
+
+
+

Supported encryption ciphers and modes

+
+

Note

+

The terms ‘cipher’ and ‘encryption algorithm’ are interchangeable.

+
+
+

Portable ciphers

+

Because MCrypt and OpenSSL (also called drivers throughout this document) +each support different sets of encryption algorithms and often implement +them in different ways, our Encryption library is designed to use them in +a portable fashion, or in other words - it enables you to use them +interchangeably, at least for the ciphers supported by both drivers.

+

It is also implemented in a way that aims to match the standard +implementations in other programming languages and libraries.

+

Here’s a list of the so called “portable” ciphers, where +“CodeIgniter name” is the string value that you’d have to pass to the +Encryption library to use that cipher:

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Cipher nameCodeIgniter nameKey lengths (bits / bytes)Supported modes
AES-128 / Rijndael-128aes-128128 / 16CBC, CTR, CFB, CFB8, OFB, ECB
AES-192aes-192192 / 24CBC, CTR, CFB, CFB8, OFB, ECB
AES-256aes-256256 / 32CBC, CTR, CFB, CFB8, OFB, ECB
DESdes56 / 7CBC, CFB, CFB8, OFB, ECB
TripleDEStripledes56 / 7, 112 / 14, 168 / 21CBC, CFB, CFB8, OFB
Blowfishblowfish128-448 / 16-56CBC, CFB, OFB, ECB
CAST5 / CAST-128cast588-128 / 11-16CBC, CFB, OFB, ECB
RC4 / ARCFourrc440-2048 / 5-256Stream
+
+

Important

+

Because of how MCrypt works, if you fail to provide a key +with the appropriate length, you might end up using a different +algorithm than the one configured, so be really careful with that!

+
+
+

Note

+

In case it isn’t clear from the above table, Blowfish, CAST5 +and RC4 support variable length keys. That is, any number in the +shown ranges is valid, although in bit terms that only happens +in 8-bit increments.

+
+
+

Note

+

Even though CAST5 supports key lengths lower than 128 bits +(16 bytes), in fact they will just be zero-padded to the +maximum length, as specified in RFC 2144.

+
+
+

Note

+

Blowfish supports key lengths as small as 32 bits (4 bytes), but +our tests have shown that only lengths of 128 bits (16 bytes) or +higher are properly supported by both MCrypt and OpenSSL. It is +also a bad practice to use such low-length keys anyway.

+
+
+
+

Driver-specific ciphers

+

As noted above, MCrypt and OpenSSL support different sets of encryption +ciphers. For portability reasons and because we haven’t tested them +properly, we do not advise you to use the ones that are driver-specific, +but regardless, here’s a list of most of them:

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Cipher nameDriverKey lengths (bits / bytes)Supported modes
AES-128OpenSSL128 / 16CBC, CTR, CFB, CFB8, OFB, ECB, XTS
AES-192OpenSSL192 / 24CBC, CTR, CFB, CFB8, OFB, ECB, XTS
AES-256OpenSSL256 / 32CBC, CTR, CFB, CFB8, OFB, ECB, XTS
Rijndael-128MCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
Rijndael-192MCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
Rijndael-256MCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
GOSTMCrypt256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
TwofishMCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
CAST-128MCrypt40-128 / 5-16CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
CAST-256MCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
Loki97MCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
SaferPlusMCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
SerpentMCrypt128 / 16, 192 / 24, 256 / 32CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
XTEAMCrypt128 / 16CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
RC2MCrypt8-1024 / 1-128CBC, CTR, CFB, CFB8, OFB, OFB8, ECB
RC2OpenSSL8-1024 / 1-128CBC, CFB, OFB, ECB
Camellia-128OpenSSL128 / 16CBC, CFB, CFB8, OFB, ECB
Camellia-192OpenSSL192 / 24CBC, CFB, CFB8, OFB, ECB
Camellia-256OpenSSL256 / 32CBC, CFB, CFB8, OFB, ECB
SeedOpenSSL128 / 16CBC, CFB, OFB, ECB
+
+

Note

+

If you wish to use one of those ciphers, you’d have to pass +its name in lower-case to the Encryption library.

+
+
+

Note

+

You’ve probably noticed that all AES cipers (and Rijndael-128) +are also listed in the portable ciphers list. This is because +drivers support different modes for these ciphers. Also, it is +important to note that AES-128 and Rijndael-128 are actually +the same cipher, but only when used with a 128-bit key.

+
+
+

Note

+

CAST-128 / CAST-5 is also listed in both the portable and +driver-specific ciphers list. This is because OpenSSL’s +implementation doesn’t appear to be working correctly with +key sizes of 80 bits and lower.

+
+
+

Note

+

RC2 is listed as supported by both MCrypt and OpenSSL. +However, both drivers implement them differently and they +are not portable. It is probably worth noting that we only +found one obscure source confirming that it is MCrypt that +is not properly implementing it.

+
+
+
+

Encryption modes

+

Different modes of encryption have different characteristics and serve +for different purposes. Some are stronger than others, some are faster +and some offer extra features. +We are not going in depth into that here, we’ll leave that to the +cryptography experts. The table below is to provide brief informational +reference to our more experienced users. If you are a beginner, just +stick to the CBC mode - it is widely accepted as strong and secure for +general purposes.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Mode nameCodeIgniter nameDriver supportAdditional info
CBCcbcMCrypt, OpenSSLA safe default choice
CTRctrMCrypt, OpenSSLConsidered as theoretically better than CBC, but not as widely available
CFBcfbMCrypt, OpenSSLN/A
CFB8cfb8MCrypt, OpenSSLSame as CFB, but operates in 8-bit mode (not recommended).
OFBofbMCrypt, OpenSSLN/A
OFB8ofb8MCryptSame as OFB, but operates in 8-bit mode (not recommended).
ECBecbMCrypt, OpenSSLIgnores IV (not recommended).
XTSxtsOpenSSLUsually used for encrypting random access data such as RAM or hard-disk storage.
StreamstreamMCrypt, OpenSSLThis is not actually a mode, it just says that a stream cipher is being used. Required because of the general cipher+mode initialization process.
+
+
+
+

Message Length

+

It’s probably important for you to know that an encrypted string is usually +longer than the original, plain-text string (depending on the cipher).

+

This is influenced by the cipher algorithm itself, the IV prepended to the +cipher-text and the HMAC authentication message that is also prepended. +Furthermore, the encrypted message is also Base64-encoded so that it is safe +for storage and transmission, regardless of a possible character set in use.

+

Keep this information in mind when selecting your data storage mechanism. +Cookies, for example, can only hold 4K of information.

+
+
+

Configuring the library

+

For usability, performance, but also historical reasons tied to our old +Encrypt Class, the Encryption library is designed to +use repeatedly the same driver, encryption cipher, mode and key.

+

As noted in the “Default behavior” section above, this means using an +auto-detected driver (OpenSSL has a higher priority), the AES-128 ciper +in CBC mode, and your $config['encryption_key'] value.

+

If you wish to change that however, you need to use the initialize() +method. It accepts an associative array of parameters, all of which are +optional:

+ ++++ + + + + + + + + + + + + + + + + + + + +
OptionPossible values
driver‘mcrypt’, ‘openssl’
cipherCipher name (see Supported encryption ciphers and modes)
modeEncryption mode (see Encryption modes)
keyEncryption key
+

For example, if you were to change the encryption algorithm and +mode to AES-256 in CTR mode, this is what you should do:

+
$this->encryption->initialize(
+        array(
+                'cipher' => 'aes-256',
+                'mode' => 'ctr',
+                'key' => '<a 32-character random string>'
+        )
+);
+
+
+

Note that we only mentioned that you want to change the ciper and mode, +but we also included a key in the example. As previously noted, it is +important that you choose a key with a proper size for the used algorithm.

+

There’s also the ability to change the driver, if for some reason you +have both, but want to use MCrypt instead of OpenSSL:

+
// Switch to the MCrypt driver
+$this->encryption->initialize(array('driver' => 'mcrypt'));
+
+// Switch back to the OpenSSL driver
+$this->encryption->initialize(array('driver' => 'openssl'));
+
+
+
+
+

Encrypting and decrypting data

+

Encrypting and decrypting data with the already configured library +settings is simple. As simple as just passing the string to the +encrypt() and/or decrypt() methods:

+
$plain_text = 'This is a plain-text message!';
+$ciphertext = $this->encryption->encrypt($plain_text);
+
+// Outputs: This is a plain-text message!
+echo $this->encryption->decrypt($ciphertext);
+
+
+

And that’s it! The Encryption library will do everything necessary +for the whole process to be cryptographically secure out-of-the-box. +You don’t need to worry about it.

+
+

Important

+

Both methods will return FALSE in case of an error. +While for encrypt() this can only mean incorrect +configuration, you should always check the return value +of decrypt() in production code.

+
+
+

How it works

+

If you must know how the process works, here’s what happens under +the hood:

+
    +
  • $this->encryption->encrypt($plain_text)
      +
    1. Derive an encryption key and a HMAC key from your configured +encryption_key via HKDF, using the SHA-512 digest algorithm.
    2. +
    3. Generate a random initialization vector (IV).
    4. +
    5. Encrypt the data via AES-128 in CBC mode (or another previously +configured cipher and mode), using the above-mentioned derived +encryption key and IV.
    6. +
    7. Prepend said IV to the resulting cipher-text.
    8. +
    9. Base64-encode the resulting string, so that it can be safely +stored or transferred without worrying about character sets.
    10. +
    11. Create a SHA-512 HMAC authentication message using the derived +HMAC key to ensure data integrity and prepend it to the Base64 +string.
    12. +
    +
  • +
  • $this->encryption->decrypt($ciphertext)
      +
    1. Derive an encryption key and a HMAC key from your configured +encryption_key via HKDF, using the SHA-512 digest algorithm. +Because your configured encryption_key is the same, this +will produce the same result as in the encrypt() method +above - otherwise you won’t be able to decrypt it.
    2. +
    3. Check if the string is long enough, separate the HMAC out of +it and validate if it is correct (this is done in a way that +prevents timing attacks against it). Return FALSE if either of +the checks fails.
    4. +
    5. Base64-decode the string.
    6. +
    7. Separate the IV out of the cipher-text and decrypt the said +cipher-text using that IV and the derived encryption key.
    8. +
    +
  • +
+
+
+

Using custom parameters

+

Let’s say you have to interact with another system that is out +of your control and uses another method to encrypt data. A +method that will most certainly not match the above-described +sequence and probably not use all of the steps either.

+

The Encryption library allows you to change how its encryption +and decryption processes work, so that you can easily tailor a +custom solution for such situations.

+
+

Note

+

It is possible to use the library in this way, without +setting an encryption_key in your configuration file.

+
+

All you have to do is to pass an associative array with a few +parameters to either the encrypt() or decrypt() method. +Here’s an example:

+
// Assume that we have $ciphertext, $key and $hmac_key
+// from on outside source
+
+$message = $this->encryption->decrypt(
+        $ciphertext,
+        array(
+                'cipher' => 'blowfish',
+                'mode' => 'cbc',
+                'key' => $key,
+                'hmac_digest' => 'sha256',
+                'hmac_key' => $hmac_key
+        )
+);
+
+
+

In the above example, we are decrypting a message that was encrypted +using the Blowfish cipher in CBC mode and authenticated via a SHA-256 +HMAC.

+
+

Important

+

Note that both ‘key’ and ‘hmac_key’ are used in this +example. When using custom parameters, encryption and HMAC keys +are not derived like the default behavior of the library is.

+
+

Below is a list of the available options.

+

However, unless you really need to and you know what you are doing, +we advise you to not change the encryption process as this could +impact security, so please do so with caution.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionDefault valueMandatory / OptionalDescription
cipherN/AYesEncryption algorithm (see Supported encryption ciphers and modes).
modeN/AYesEncryption mode (see Encryption modes).
keyN/AYesEncryption key.
hmacTRUENoWhether to use a HMAC. +Boolean. If set to FALSE, then hmac_digest and +hmac_key will be ignored.
hmac_digestsha512NoHMAC message digest algorithm (see Supported HMAC authentication algorithms).
hmac_keyN/AYes, unless hmac is FALSEHMAC key.
raw_dataFALSENoWhether the cipher-text should be raw. +Boolean. If set to TRUE, then Base64 encoding and +decoding will not be performed and HMAC will not +be a hexadecimal string.
+
+

Important

+

encrypt() and decrypt() will return FALSE if +a mandatory parameter is not provided or if a provided +value is incorrect. This includes hmac_key, unless hmac +is set to FALSE.

+
+
+
+

Supported HMAC authentication algorithms

+

For HMAC message authentication, the Encryption library supports +usage of the SHA-2 family of algorithms:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
AlgorithmRaw length (bytes)Hex-encoded length (bytes)
sha51264128
sha3844896
sha2563264
sha2242856
+

The reason for not including other popular algorithms, such as +MD5 or SHA1 is that they are no longer considered secure enough +and as such, we don’t want to encourage their usage. +If you absolutely need to use them, it is easy to do so via PHP’s +native hash_hmac() function.

+

Stronger algorithms of course will be added in the future as they +appear and become widely available.

+
+
+
+
+

Class Reference

+
+
+class CI_Encryption
+
+
+initialize($params)
+
+++ + + + + + + + +
Parameters:
    +
  • $params (array) – Configuration parameters
  • +
+
Returns:

CI_Encryption instance (method chaining)

+
Return type:

CI_Encryption

+
+

Initializes (configures) the library to use a different +driver, cipher, mode or key.

+

Example:

+
$this->encryption->initialize(
+        array('mode' => 'ctr')
+);
+
+
+

Please refer to the Configuring the library section for detailed info.

+
+ +
+
+encrypt($data[, $params = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $data (string) – Data to encrypt
  • +
  • $params (array) – Optional parameters
  • +
+
Returns:

Encrypted data or FALSE on failure

+
Return type:

string

+
+

Encrypts the input data and returns its ciphertext.

+

Example:

+
$ciphertext = $this->encryption->encrypt('My secret message');
+
+
+

Please refer to the Using custom parameters section for information +on the optional parameters.

+
+ +
+
+decrypt($data[, $params = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $data (string) – Data to decrypt
  • +
  • $params (array) – Optional parameters
  • +
+
Returns:

Decrypted data or FALSE on failure

+
Return type:

string

+
+

Decrypts the input data and returns it in plain-text.

+

Example:

+
echo $this->encryption->decrypt($ciphertext);
+
+
+

Please refer to the Using custom parameters secrion for information +on the optional parameters.

+
+ +
+
+create_key($length)
+
+++ + + + + + + + +
Parameters:
    +
  • $length (int) – Output length
  • +
+
Returns:

A pseudo-random cryptographic key with the specified length, or FALSE on failure

+
Return type:

string

+
+

Creates a cryptographic key by fetching random data from +the operating system’s sources (i.e. /dev/urandom).

+
+ +
+
+hkdf($key[, $digest = 'sha512'[, $salt = NULL[, $length = NULL[, $info = '']]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Input key material
  • +
  • $digest (string) – A SHA-2 family digest algorithm
  • +
  • $salt (string) – Optional salt
  • +
  • $length (int) – Optional output length
  • +
  • $info (string) – Optional context/application-specific info
  • +
+
Returns:

A pseudo-random key or FALSE on failure

+
Return type:

string

+
+

Derives a key from another, presumably weaker key.

+

This method is used internally to derive an encryption and HMAC key +from your configured encryption_key.

+

It is publicly available due to its otherwise general purpose. It is +described in RFC 5869.

+

However, as opposed to the description in RFC 5869, this implementation +doesn’t support SHA1.

+

Example:

+
$hmac_key = $this->encryption->hkdf(
+        $key,
+        'sha512',
+        NULL,
+        NULL,
+        'authentication'
+);
+
+// $hmac_key is a pseudo-random key with a length of 64 bytes
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/file_uploading.html b/user_guide/libraries/file_uploading.html new file mode 100644 index 000000000..6870f698d --- /dev/null +++ b/user_guide/libraries/file_uploading.html @@ -0,0 +1,1025 @@ + + + + + + + + + + File Uploading Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • File Uploading Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

File Uploading Class

+

CodeIgniter’s File Uploading Class permits files to be uploaded. You can +set various preferences, restricting the type and size of the files.

+ +
+

The Process

+

Uploading a file involves the following general process:

+
    +
  • An upload form is displayed, allowing a user to select a file and +upload it.
  • +
  • When the form is submitted, the file is uploaded to the destination +you specify.
  • +
  • Along the way, the file is validated to make sure it is allowed to be +uploaded based on the preferences you set.
  • +
  • Once uploaded, the user will be shown a success message.
  • +
+

To demonstrate this process here is brief tutorial. Afterward you’ll +find reference information.

+
+

Creating the Upload Form

+

Using a text editor, create a form called upload_form.php. In it, place +this code and save it to your application/views/ directory:

+
<html>
+<head>
+<title>Upload Form</title>
+</head>
+<body>
+
+<?php echo $error;?>
+
+<?php echo form_open_multipart('upload/do_upload');?>
+
+<input type="file" name="userfile" size="20" />
+
+<br /><br />
+
+<input type="submit" value="upload" />
+
+</form>
+
+</body>
+</html>
+
+
+

You’ll notice we are using a form helper to create the opening form tag. +File uploads require a multipart form, so the helper creates the proper +syntax for you. You’ll also notice we have an $error variable. This is +so we can show error messages in the event the user does something +wrong.

+
+
+

The Success Page

+

Using a text editor, create a form called upload_success.php. In it, +place this code and save it to your application/views/ directory:

+
<html>
+<head>
+<title>Upload Form</title>
+</head>
+<body>
+
+<h3>Your file was successfully uploaded!</h3>
+
+<ul>
+<?php foreach ($upload_data as $item => $value):?>
+<li><?php echo $item;?>: <?php echo $value;?></li>
+<?php endforeach; ?>
+</ul>
+
+<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
+
+</body>
+</html>
+
+
+
+
+

The Controller

+

Using a text editor, create a controller called Upload.php. In it, place +this code and save it to your application/controllers/ directory:

+
<?php
+
+class Upload extends CI_Controller {
+
+        public function __construct()
+        {
+                parent::__construct();
+                $this->load->helper(array('form', 'url'));
+        }
+
+        public function index()
+        {
+                $this->load->view('upload_form', array('error' => ' ' ));
+        }
+
+        public function do_upload()
+        {
+                $config['upload_path']          = './uploads/';
+                $config['allowed_types']        = 'gif|jpg|png';
+                $config['max_size']             = 100;
+                $config['max_width']            = 1024;
+                $config['max_height']           = 768;
+
+                $this->load->library('upload', $config);
+
+                if ( ! $this->upload->do_upload('userfile'))
+                {
+                        $error = array('error' => $this->upload->display_errors());
+
+                        $this->load->view('upload_form', $error);
+                }
+                else
+                {
+                        $data = array('upload_data' => $this->upload->data());
+
+                        $this->load->view('upload_success', $data);
+                }
+        }
+}
+?>
+
+
+
+
+

The Upload Directory

+

You’ll need a destination directory for your uploaded images. Create a +directory at the root of your CodeIgniter installation called uploads +and set its file permissions to 777.

+
+
+

Try it!

+

To try your form, visit your site using a URL similar to this one:

+
example.com/index.php/upload/
+
+
+

You should see an upload form. Try uploading an image file (either a +jpg, gif, or png). If the path in your controller is correct it should +work.

+
+
+
+

Reference Guide

+
+

Initializing the Upload Class

+

Like most other classes in CodeIgniter, the Upload class is initialized +in your controller using the $this->load->library() method:

+
$this->load->library('upload');
+
+
+

Once the Upload class is loaded, the object will be available using: +$this->upload

+
+
+

Setting Preferences

+

Similar to other libraries, you’ll control what is allowed to be upload +based on your preferences. In the controller you built above you set the +following preferences:

+
$config['upload_path'] = './uploads/';
+$config['allowed_types'] = 'gif|jpg|png';
+$config['max_size']     = '100';
+$config['max_width'] = '1024';
+$config['max_height'] = '768';
+
+$this->load->library('upload', $config);
+
+// Alternately you can set preferences by calling the ``initialize()`` method. Useful if you auto-load the class:
+$this->upload->initialize($config);
+
+
+

The above preferences should be fairly self-explanatory. Below is a +table describing all available preferences.

+
+
+

Preferences

+

The following preferences are available. The default value indicates +what will be used if you do not specify that preference.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
upload_pathNoneNoneThe path to the directory where the upload should be placed. The +directory must be writable and the path can be absolute or relative.
allowed_typesNoneNoneThe mime types corresponding to the types of files you allow to be +uploaded. Usually the file extension can be used as the mime type. +Can be either an array or a pipe-separated string.
file_nameNoneDesired file nameIf set CodeIgniter will rename the uploaded file to this name. The +extension provided in the file name must also be an allowed file type. +If no extension is provided in the original file_name will be used.
file_ext_tolowerFALSETRUE/FALSE (boolean)If set to TRUE, the file extension will be forced to lower case
overwriteFALSETRUE/FALSE (boolean)If set to true, if a file with the same name as the one you are +uploading exists, it will be overwritten. If set to false, a number will +be appended to the filename if another with the same name exists.
max_size0NoneThe maximum size (in kilobytes) that the file can be. Set to zero for no +limit. Note: Most PHP installations have their own limit, as specified +in the php.ini file. Usually 2 MB (or 2048 KB) by default.
max_width0NoneThe maximum width (in pixels) that the image can be. Set to zero for no +limit.
max_height0NoneThe maximum height (in pixels) that the image can be. Set to zero for no +limit.
min_width0NoneThe minimum width (in pixels) that the image can be. Set to zero for no +limit.
min_height0NoneThe minimum height (in pixels) that the image can be. Set to zero for no +limit.
max_filename0NoneThe maximum length that a file name can be. Set to zero for no limit.
max_filename_increment100NoneWhen overwrite is set to FALSE, use this to set the maximum filename +increment for CodeIgniter to append to the filename.
encrypt_nameFALSETRUE/FALSE (boolean)If set to TRUE the file name will be converted to a random encrypted +string. This can be useful if you would like the file saved with a name +that can not be discerned by the person uploading it.
remove_spacesTRUETRUE/FALSE (boolean)If set to TRUE, any spaces in the file name will be converted to +underscores. This is recommended.
detect_mimeTRUETRUE/FALSE (boolean)If set to TRUE, a server side detection of the file type will be +performed to avoid code injection attacks. DO NOT disable this option +unless you have no other option as that would cause a security risk.
mod_mime_fixTRUETRUE/FALSE (boolean)If set to TRUE, multiple filename extensions will be suffixed with an +underscore in order to avoid triggering Apache mod_mime. +DO NOT turn off this option if your upload directory is public, as this +is a security risk.
+
+
+

Setting preferences in a config file

+

If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called the +upload.php, add the $config array in that file. Then save the file in: +config/upload.php and it will be used automatically. You will NOT +need to use the $this->upload->initialize() method if you save your +preferences in a config file.

+
+
+
+

Class Reference

+
+
+class CI_Upload
+
+
+initialize([array $config = array()[, $reset = TRUE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $config (array) – Preferences
  • +
  • $reset (bool) – Whether to reset preferences (that are not provided in $config) to their defaults
  • +
+
Returns:

CI_Upload instance (method chaining)

+
Return type:

CI_Upload

+
+
+ +
+
+do_upload([$field = 'userfile'])
+
+++ + + + + + + + +
Parameters:
    +
  • $field (string) – Name of the form field
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Performs the upload based on the preferences you’ve set.

+
+

Note

+

By default the upload routine expects the file to come from +a form field called userfile, and the form must be of type +“multipart”.

+
+
<form method="post" action="some_action" enctype="multipart/form-data" />
+
+
+

If you would like to set your own field name simply pass its value to +the do_upload() method:

+
$field_name = "some_field_name";
+$this->upload->do_upload($field_name);
+
+
+
+ +
+
+display_errors([$open = '<p>'[, $close = '</p>']])
+
+++ + + + + + + + +
Parameters:
    +
  • $open (string) – Opening markup
  • +
  • $close (string) – Closing markup
  • +
+
Returns:

Formatted error message(s)

+
Return type:

string

+
+

Retrieves any error messages if the do_upload() method returned +false. The method does not echo automatically, it returns the data so +you can assign it however you need.

+

Formatting Errors

+
+

By default the above method wraps any errors within <p> tags. You can +set your own delimiters like this:

+
$this->upload->display_errors('<p>', '</p>');
+
+
+
+
+ +
+
+data([$index = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $data (string) – Element to return instead of the full array
  • +
+
Returns:

Information about the uploaded file

+
Return type:

mixed

+
+

This is a helper method that returns an array containing all of the +data related to the file you uploaded. Here is the array prototype:

+
Array
+(
+        [file_name]     => mypic.jpg
+        [file_type]     => image/jpeg
+        [file_path]     => /path/to/your/upload/
+        [full_path]     => /path/to/your/upload/jpg.jpg
+        [raw_name]      => mypic
+        [orig_name]     => mypic.jpg
+        [client_name]   => mypic.jpg
+        [file_ext]      => .jpg
+        [file_size]     => 22.2
+        [is_image]      => 1
+        [image_width]   => 800
+        [image_height]  => 600
+        [image_type]    => jpeg
+        [image_size_str] => width="800" height="200"
+)
+
+
+

To return one element from the array:

+
$this->upload->data('file_name');       // Returns: mypic.jpg
+
+
+

Here’s a table explaining the above-displayed array items:

+ ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ItemDescription
file_nameName of the file that was uploaded, including the filename extension
file_typeFile MIME type identifier
file_pathAbsolute server path to the file
full_pathAbsolute server path, including the file name
raw_nameFile name, without the extension
orig_nameOriginal file name. This is only useful if you use the encrypted name option.
client_nameFile name as supplied by the client user agent, prior to any file name preparation or incrementing
file_extFilename extension, period included
file_sizeFile size in kilobytes
is_imageWhether the file is an image or not. 1 = image. 0 = not.
image_widthImage width
image_heightImage height
image_typeImage type (usually the file name extension without the period)
image_size_strA string containing the width and height (useful to put into an image tag)
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/form_validation.html b/user_guide/libraries/form_validation.html new file mode 100644 index 000000000..3d9da783b --- /dev/null +++ b/user_guide/libraries/form_validation.html @@ -0,0 +1,1932 @@ + + + + + + + + + + Form Validation — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Form Validation

+

CodeIgniter provides a comprehensive form validation and data prepping +class that helps minimize the amount of code you’ll write.

+ +
+

Overview

+

Before explaining CodeIgniter’s approach to data validation, let’s +describe the ideal scenario:

+
    +
  1. A form is displayed.
  2. +
  3. You fill it in and submit it.
  4. +
  5. If you submitted something invalid, or perhaps missed a required +item, the form is redisplayed containing your data along with an +error message describing the problem.
  6. +
  7. This process continues until you have submitted a valid form.
  8. +
+

On the receiving end, the script must:

+
    +
  1. Check for required data.
  2. +
  3. Verify that the data is of the correct type, and meets the correct +criteria. For example, if a username is submitted it must be +validated to contain only permitted characters. It must be of a +minimum length, and not exceed a maximum length. The username can’t +be someone else’s existing username, or perhaps even a reserved word. +Etc.
  4. +
  5. Sanitize the data for security.
  6. +
  7. Pre-format the data if needed (Does the data need to be trimmed? HTML +encoded? Etc.)
  8. +
  9. Prep the data for insertion in the database.
  10. +
+

Although there is nothing terribly complex about the above process, it +usually requires a significant amount of code, and to display error +messages, various control structures are usually placed within the form +HTML. Form validation, while simple to create, is generally very messy +and tedious to implement.

+
+
+

Form Validation Tutorial

+

What follows is a “hands on” tutorial for implementing CodeIgniters Form +Validation.

+

In order to implement form validation you’ll need three things:

+
    +
  1. A View file containing a form.
  2. +
  3. A View file containing a “success” message to be displayed upon +successful submission.
  4. +
  5. A controller method to receive and +process the submitted data.
  6. +
+

Let’s create those three things, using a member sign-up form as the +example.

+
+

The Form

+

Using a text editor, create a form called myform.php. In it, place this +code and save it to your application/views/ folder:

+
<html>
+<head>
+<title>My Form</title>
+</head>
+<body>
+
+<?php echo validation_errors(); ?>
+
+<?php echo form_open('form'); ?>
+
+<h5>Username</h5>
+<input type="text" name="username" value="" size="50" />
+
+<h5>Password</h5>
+<input type="text" name="password" value="" size="50" />
+
+<h5>Password Confirm</h5>
+<input type="text" name="passconf" value="" size="50" />
+
+<h5>Email Address</h5>
+<input type="text" name="email" value="" size="50" />
+
+<div><input type="submit" value="Submit" /></div>
+
+</form>
+
+</body>
+</html>
+
+
+
+
+

The Success Page

+

Using a text editor, create a form called formsuccess.php. In it, place +this code and save it to your application/views/ folder:

+
<html>
+<head>
+<title>My Form</title>
+</head>
+<body>
+
+<h3>Your form was successfully submitted!</h3>
+
+<p><?php echo anchor('form', 'Try it again!'); ?></p>
+
+</body>
+</html>
+
+
+
+
+

The Controller

+

Using a text editor, create a controller called Form.php. In it, place +this code and save it to your application/controllers/ folder:

+
<?php
+
+class Form extends CI_Controller {
+
+        public function index()
+        {
+                $this->load->helper(array('form', 'url'));
+
+                $this->load->library('form_validation');
+
+                if ($this->form_validation->run() == FALSE)
+                {
+                        $this->load->view('myform');
+                }
+                else
+                {
+                        $this->load->view('formsuccess');
+                }
+        }
+}
+
+
+
+
+

Try it!

+

To try your form, visit your site using a URL similar to this one:

+
example.com/index.php/form/
+
+
+

If you submit the form you should simply see the form reload. That’s +because you haven’t set up any validation rules yet.

+

Since you haven’t told the Form Validation class to validate anything +yet, it returns FALSE (boolean false) by default. ``The run()`` method +only returns TRUE if it has successfully applied your rules without any +of them failing.

+
+
+

Explanation

+

You’ll notice several things about the above pages:

+

The form (myform.php) is a standard web form with a couple exceptions:

+
    +
  1. It uses a form helper to create the form opening. Technically, this +isn’t necessary. You could create the form using standard HTML. +However, the benefit of using the helper is that it generates the +action URL for you, based on the URL in your config file. This makes +your application more portable in the event your URLs change.

    +
  2. +
  3. At the top of the form you’ll notice the following function call:

    +
    <?php echo validation_errors(); ?>
    +
    +
    +

    This function will return any error messages sent back by the +validator. If there are no messages it returns an empty string.

    +
  4. +
+

The controller (Form.php) has one method: index(). This method +initializes the validation class and loads the form helper and URL +helper used by your view files. It also runs the validation routine. +Based on whether the validation was successful it either presents the +form or the success page.

+
+
+

Setting Validation Rules

+

CodeIgniter lets you set as many validation rules as you need for a +given field, cascading them in order, and it even lets you prep and +pre-process the field data at the same time. To set validation rules you +will use the set_rules() method:

+
$this->form_validation->set_rules();
+
+
+

The above method takes three parameters as input:

+
    +
  1. The field name - the exact name you’ve given the form field.
  2. +
  3. A “human” name for this field, which will be inserted into the error +message. For example, if your field is named “user” you might give it +a human name of “Username”.
  4. +
  5. The validation rules for this form field.
  6. +
  7. (optional) Set custom error messages on any rules given for current field. If not provided will use the default one.
  8. +
+
+

Note

+

If you would like the field name to be stored in a language +file, please see Translating Field Names.

+
+

Here is an example. In your controller (Form.php), add this code just +below the validation initialization method:

+
$this->form_validation->set_rules('username', 'Username', 'required');
+$this->form_validation->set_rules('password', 'Password', 'required');
+$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
+$this->form_validation->set_rules('email', 'Email', 'required');
+
+
+

Your controller should now look like this:

+
<?php
+
+class Form extends CI_Controller {
+
+        public function index()
+        {
+                $this->load->helper(array('form', 'url'));
+
+                $this->load->library('form_validation');
+
+                $this->form_validation->set_rules('username', 'Username', 'required');
+                $this->form_validation->set_rules('password', 'Password', 'required',
+                        array('required' => 'You must provide a %s.')
+                );
+                $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
+                $this->form_validation->set_rules('email', 'Email', 'required');
+
+                if ($this->form_validation->run() == FALSE)
+                {
+                        $this->load->view('myform');
+                }
+                else
+                {
+                        $this->load->view('formsuccess');
+                }
+        }
+}
+
+
+

Now submit the form with the fields blank and you should see the error +messages. If you submit the form with all the fields populated you’ll +see your success page.

+
+

Note

+

The form fields are not yet being re-populated with the data +when there is an error. We’ll get to that shortly.

+
+
+
+

Setting Rules Using an Array

+

Before moving on it should be noted that the rule setting method can +be passed an array if you prefer to set all your rules in one action. If +you use this approach, you must name your array keys as indicated:

+
$config = array(
+        array(
+                'field' => 'username',
+                'label' => 'Username',
+                'rules' => 'required'
+        ),
+        array(
+                'field' => 'password',
+                'label' => 'Password',
+                'rules' => 'required',
+                'errors' => array(
+                        'required' => 'You must provide a %s.',
+                ),
+        ),
+        array(
+                'field' => 'passconf',
+                'label' => 'Password Confirmation',
+                'rules' => 'required'
+        ),
+        array(
+                'field' => 'email',
+                'label' => 'Email',
+                'rules' => 'required'
+        )
+);
+
+$this->form_validation->set_rules($config);
+
+
+
+
+

Cascading Rules

+

CodeIgniter lets you pipe multiple rules together. Let’s try it. Change +your rules in the third parameter of rule setting method, like this:

+
$this->form_validation->set_rules(
+        'username', 'Username',
+        'required|min_length[5]|max_length[12]|is_unique[users.username]',
+        array(
+                'required'      => 'You have not provided %s.',
+                'is_unique'     => 'This %s already exists.'
+        )
+);
+$this->form_validation->set_rules('password', 'Password', 'required');
+$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]');
+$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
+
+
+

The above code sets the following rules:

+
    +
  1. The username field be no shorter than 5 characters and no longer than +12.
  2. +
  3. The password field must match the password confirmation field.
  4. +
  5. The email field must contain a valid email address.
  6. +
+

Give it a try! Submit your form without the proper data and you’ll see +new error messages that correspond to your new rules. There are numerous +rules available which you can read about in the validation reference.

+
+

Note

+

You can also pass an array of rules to set_rules(), +instead of a string. Example:

+
$this->form_validation->set_rules('username', 'Username', array('required', 'min_length[5]'));
+
+
+
+
+
+

Prepping Data

+

In addition to the validation method like the ones we used above, you +can also prep your data in various ways. For example, you can set up +rules like this:

+
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]');
+$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]');
+$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
+$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
+
+
+

In the above example, we are “trimming” the fields, checking for length +where necessary and making sure that both password fields match.

+

Any native PHP function that accepts one parameter can be used as a +rule, like ``htmlspecialchars()``, ``trim()``, etc.

+
+

Note

+

You will generally want to use the prepping functions +after the validation rules so if there is an error, the +original data will be shown in the form.

+
+
+
+

Re-populating the form

+

Thus far we have only been dealing with errors. It’s time to repopulate +the form field with the submitted data. CodeIgniter offers several +helper functions that permit you to do this. The one you will use most +commonly is:

+
set_value('field name')
+
+
+

Open your myform.php view file and update the value in each field +using the set_value() function:

+

Don’t forget to include each field name in the :php:func:`set_value()` +function calls!

+
<html>
+<head>
+<title>My Form</title>
+</head>
+<body>
+
+<?php echo validation_errors(); ?>
+
+<?php echo form_open('form'); ?>
+
+<h5>Username</h5>
+<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
+
+<h5>Password</h5>
+<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
+
+<h5>Password Confirm</h5>
+<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
+
+<h5>Email Address</h5>
+<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
+
+<div><input type="submit" value="Submit" /></div>
+
+</form>
+
+</body>
+</html>
+
+
+

Now reload your page and submit the form so that it triggers an error. +Your form fields should now be re-populated

+
+

Note

+

The Class Reference section below +contains methods that permit you to re-populate <select> menus, +radio buttons, and checkboxes.

+
+
+

Important

+

If you use an array as the name of a form field, you +must supply it as an array to the function. Example:

+
<input type="text" name="colors[]" value="<?php echo set_value('colors[]'); ?>" size="50" />
+
+
+
+

For more info please see the Using Arrays as Field Names section below.

+
+
+

Callbacks: Your own Validation Methods

+

The validation system supports callbacks to your own validation +methods. This permits you to extend the validation class to meet your +needs. For example, if you need to run a database query to see if the +user is choosing a unique username, you can create a callback method +that does that. Let’s create an example of this.

+

In your controller, change the “username” rule to this:

+
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
+
+
+

Then add a new method called username_check() to your controller. +Here’s how your controller should now look:

+
<?php
+
+class Form extends CI_Controller {
+
+        public function index()
+        {
+                $this->load->helper(array('form', 'url'));
+
+                $this->load->library('form_validation');
+
+                $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
+                $this->form_validation->set_rules('password', 'Password', 'required');
+                $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
+                $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
+
+                if ($this->form_validation->run() == FALSE)
+                {
+                        $this->load->view('myform');
+                }
+                else
+                {
+                        $this->load->view('formsuccess');
+                }
+        }
+
+        public function username_check($str)
+        {
+                if ($str == 'test')
+                {
+                        $this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
+                        return FALSE;
+                }
+                else
+                {
+                        return TRUE;
+                }
+        }
+
+}
+
+
+

Reload your form and submit it with the word “test” as the username. You +can see that the form field data was passed to your callback method +for you to process.

+

To invoke a callback just put the method name in a rule, with +“callback_” as the rule prefix. If you need to receive an extra +parameter in your callback method, just add it normally after the +method name between square brackets, as in: callback_foo[bar], +then it will be passed as the second argument of your callback method.

+
+

Note

+

You can also process the form data that is passed to your +callback and return it. If your callback returns anything other than a +boolean TRUE/FALSE it is assumed that the data is your newly processed +form data.

+
+
+
+

Callable: Use anything as a rule

+

If callback rules aren’t good enough for you (for example, because they are +limited to your controller), don’t get disappointed, there’s one more way +to create custom rules: anything that is_callable() would return TRUE for.

+

Consider the following example:

+
$this->form_validation->set_rules(
+        'username', 'Username',
+        array(
+                'required',
+                array($this->users_model, 'valid_username')
+        )
+);
+
+
+

The above code would use the valid_username() method from your +Users_model object.

+

This is just an example of course, and callbacks aren’t limited to models. +You can use any object/method that accepts the field value as its’ first +parameter. You can also use an anonymous function:

+
$this->form_validation->set_rules(
+        'username', 'Username',
+        array(
+                'required',
+                function($value)
+                {
+                        // Check $value
+                }
+        )
+);
+
+
+

Of course, since a Callable rule by itself is not a string, it isn’t +a rule name either. That is a problem when you want to set error messages +for them. In order to get around that problem, you can put such rules as +the second element of an array, with the first one being the rule name:

+
$this->form_validation->set_rules(
+        'username', 'Username',
+        array(
+                'required',
+                array('username_callable', array($this->users_model, 'valid_username'))
+        )
+);
+
+
+

Anonymous function version:

+
$this->form_validation->set_rules(
+        'username', 'Username',
+        array(
+                'required',
+                array(
+                        'username_callable',
+                        function($str)
+                        {
+                                // Check validity of $str and return TRUE or FALSE
+                        }
+                )
+        )
+);
+
+
+
+
+

Setting Error Messages

+

All of the native error messages are located in the following language +file: system/language/english/form_validation_lang.php

+

To set your own global custom message for a rule, you can either +extend/override the language file by creating your own in +application/language/english/form_validation_lang.php (read more +about this in the Language Class documentation), +or use the following method:

+
$this->form_validation->set_message('rule', 'Error Message');
+
+
+

If you need to set a custom error message for a particular field on +some particular rule, use the set_rules() method:

+
$this->form_validation->set_rules('field_name', 'Field Label', 'rule1|rule2|rule3',
+        array('rule2' => 'Error Message on rule2 for this field_name')
+);
+
+
+

Where rule corresponds to the name of a particular rule, and Error +Message is the text you would like displayed.

+

If you’d like to include a field’s “human” name, or the optional +parameter some rules allow for (such as max_length), you can add the +{field} and {param} tags to your message, respectively:

+
$this->form_validation->set_message('min_length', '{field} must have at least {param} characters.');
+
+
+

On a field with the human name Username and a rule of min_length[5], an +error would display: “Username must have at least 5 characters.”

+
+

Note

+

The old sprintf() method of using %s in your error messages +will still work, however it will override the tags above. You should +use one or the other.

+
+

In the callback rule example above, the error message was set by passing +the name of the method (without the “callback_” prefix):

+
$this->form_validation->set_message('username_check')
+
+
+
+
+

Translating Field Names

+

If you would like to store the “human” name you passed to the +set_rules() method in a language file, and therefore make the name +able to be translated, here’s how:

+

First, prefix your “human” name with lang:, as in this example:

+
$this->form_validation->set_rules('first_name', 'lang:first_name', 'required');
+
+
+

Then, store the name in one of your language file arrays (without the +prefix):

+
$lang['first_name'] = 'First Name';
+
+
+
+

Note

+

If you store your array item in a language file that is not +loaded automatically by CI, you’ll need to remember to load it in your +controller using:

+
$this->lang->load('file_name');
+
+
+
+

See the Language Class page for more info regarding +language files.

+
+
+

Changing the Error Delimiters

+

By default, the Form Validation class adds a paragraph tag (<p>) around +each error message shown. You can either change these delimiters +globally, individually, or change the defaults in a config file.

+
    +
  1. Changing delimiters Globally +To globally change the error delimiters, in your controller method, +just after loading the Form Validation class, add this:

    +
    $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
    +
    +
    +

    In this example, we’ve switched to using div tags.

    +
  2. +
  3. Changing delimiters Individually +Each of the two error generating functions shown in this tutorial can +be supplied their own delimiters as follows:

    +
    <?php echo form_error('field name', '<div class="error">', '</div>'); ?>
    +
    +
    +

    Or:

    +
    <?php echo validation_errors('<div class="error">', '</div>'); ?>
    +
    +
    +
  4. +
  5. Set delimiters in a config file +You can add your error delimiters in application/config/form_validation.php as follows:

    +
    $config['error_prefix'] = '<div class="error_prefix">';
    +$config['error_suffix'] = '</div>';
    +
    +
    +
  6. +
+
+
+

Showing Errors Individually

+

If you prefer to show an error message next to each form field, rather +than as a list, you can use the form_error() function.

+

Try it! Change your form so that it looks like this:

+
<h5>Username</h5>
+<?php echo form_error('username'); ?>
+<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
+
+<h5>Password</h5>
+<?php echo form_error('password'); ?>
+<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
+
+<h5>Password Confirm</h5>
+<?php echo form_error('passconf'); ?>
+<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
+
+<h5>Email Address</h5>
+<?php echo form_error('email'); ?>
+<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
+
+
+

If there are no errors, nothing will be shown. If there is an error, the +message will appear.

+
+

Important

+

If you use an array as the name of a form field, you +must supply it as an array to the function. Example:

+
<?php echo form_error('options[size]'); ?>
+<input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" />
+
+
+
+

For more info please see the Using Arrays as Field Names section below.

+
+
+

Validating an Array (other than $_POST)

+

Sometimes you may want to validate an array that does not originate from $_POST data.

+

In this case, you can specify the array to be validated:

+
$data = array(
+        'username' => 'johndoe',
+        'password' => 'mypassword',
+        'passconf' => 'mypassword'
+);
+
+$this->form_validation->set_data($data);
+
+
+

Creating validation rules, running the validation, and retrieving error +messages works the same whether you are validating $_POST data or +another array of your choice.

+
+

Important

+

You have to call the set_data() method before defining +any validation rules.

+
+
+

Important

+

If you want to validate more than one array during a single +execution, then you should call the reset_validation() method +before setting up rules and validating the new array.

+
+

For more info please see the Class Reference section below.

+
+
+
+

Saving Sets of Validation Rules to a Config File

+

A nice feature of the Form Validation class is that it permits you to +store all your validation rules for your entire application in a config +file. You can organize these rules into “groups”. These groups can +either be loaded automatically when a matching controller/method is +called, or you can manually call each set as needed.

+
+

How to save your rules

+

To store your validation rules, simply create a file named +form_validation.php in your application/config/ folder. In that file +you will place an array named $config with your rules. As shown earlier, +the validation array will have this prototype:

+
$config = array(
+        array(
+                'field' => 'username',
+                'label' => 'Username',
+                'rules' => 'required'
+        ),
+        array(
+                'field' => 'password',
+                'label' => 'Password',
+                'rules' => 'required'
+        ),
+        array(
+                'field' => 'passconf',
+                'label' => 'Password Confirmation',
+                'rules' => 'required'
+        ),
+        array(
+                'field' => 'email',
+                'label' => 'Email',
+                'rules' => 'required'
+        )
+);
+
+
+

Your validation rule file will be loaded automatically and used when you +call the run() method.

+

Please note that you MUST name your $config array.

+
+
+

Creating Sets of Rules

+

In order to organize your rules into “sets” requires that you place them +into “sub arrays”. Consider the following example, showing two sets of +rules. We’ve arbitrarily called these two rules “signup” and “email”. +You can name your rules anything you want:

+
$config = array(
+        'signup' => array(
+                array(
+                        'field' => 'username',
+                        'label' => 'Username',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'password',
+                        'label' => 'Password',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'passconf',
+                        'label' => 'Password Confirmation',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'email',
+                        'label' => 'Email',
+                        'rules' => 'required'
+                )
+        ),
+        'email' => array(
+                array(
+                        'field' => 'emailaddress',
+                        'label' => 'EmailAddress',
+                        'rules' => 'required|valid_email'
+                ),
+                array(
+                        'field' => 'name',
+                        'label' => 'Name',
+                        'rules' => 'required|alpha'
+                ),
+                array(
+                        'field' => 'title',
+                        'label' => 'Title',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'message',
+                        'label' => 'MessageBody',
+                        'rules' => 'required'
+                )
+        )
+);
+
+
+
+
+

Calling a Specific Rule Group

+

In order to call a specific group, you will pass its name to the run() +method. For example, to call the signup rule you will do this:

+
if ($this->form_validation->run('signup') == FALSE)
+{
+        $this->load->view('myform');
+}
+else
+{
+        $this->load->view('formsuccess');
+}
+
+
+
+
+

Associating a Controller Method with a Rule Group

+

An alternate (and more automatic) method of calling a rule group is to +name it according to the controller class/method you intend to use it +with. For example, let’s say you have a controller named Member and a +method named signup. Here’s what your class might look like:

+
<?php
+
+class Member extends CI_Controller {
+
+        public function signup()
+        {
+                $this->load->library('form_validation');
+
+                if ($this->form_validation->run() == FALSE)
+                {
+                        $this->load->view('myform');
+                }
+                else
+                {
+                        $this->load->view('formsuccess');
+                }
+        }
+}
+
+
+

In your validation config file, you will name your rule group +member/signup:

+
$config = array(
+        'member/signup' => array(
+                array(
+                        'field' => 'username',
+                        'label' => 'Username',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'password',
+                        'label' => 'Password',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'passconf',
+                        'label' => 'PasswordConfirmation',
+                        'rules' => 'required'
+                ),
+                array(
+                        'field' => 'email',
+                        'label' => 'Email',
+                        'rules' => 'required'
+                )
+        )
+);
+
+
+

When a rule group is named identically to a controller class/method it +will be used automatically when the run() method is invoked from that +class/method.

+
+
+
+

Using Arrays as Field Names

+

The Form Validation class supports the use of arrays as field names. +Consider this example:

+
<input type="text" name="options[]" value="" size="50" />
+
+
+

If you do use an array as a field name, you must use the EXACT array +name in the Helper Functions that require the +field name, and as your Validation Rule field name.

+

For example, to set a rule for the above field you would use:

+
$this->form_validation->set_rules('options[]', 'Options', 'required');
+
+
+

Or, to show an error for the above field you would use:

+
<?php echo form_error('options[]'); ?>
+
+
+

Or to re-populate the field you would use:

+
<input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" />
+
+
+

You can use multidimensional arrays as field names as well. For example:

+
<input type="text" name="options[size]" value="" size="50" />
+
+
+

Or even:

+
<input type="text" name="sports[nba][basketball]" value="" size="50" />
+
+
+

As with our first example, you must use the exact array name in the +helper functions:

+
<?php echo form_error('sports[nba][basketball]'); ?>
+
+
+

If you are using checkboxes (or other fields) that have multiple +options, don’t forget to leave an empty bracket after each option, so +that all selections will be added to the POST array:

+
<input type="checkbox" name="options[]" value="red" />
+<input type="checkbox" name="options[]" value="blue" />
+<input type="checkbox" name="options[]" value="green" />
+
+
+

Or if you use a multidimensional array:

+
<input type="checkbox" name="options[color][]" value="red" />
+<input type="checkbox" name="options[color][]" value="blue" />
+<input type="checkbox" name="options[color][]" value="green" />
+
+
+

When you use a helper function you’ll include the bracket as well:

+
<?php echo form_error('options[color][]'); ?>
+
+
+
+
+

Rule Reference

+

The following is a list of all the native rules that are available to +use:

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RuleParameterDescriptionExample
requiredNoReturns FALSE if the form element is empty. 
matchesYesReturns FALSE if the form element does not match the one in the parameter.matches[form_item]
regex_matchYesReturns FALSE if the form element does not match the regular expression.regex_match[/regex/]
differsYesReturns FALSE if the form element does not differ from the one in the parameter.differs[form_item]
is_uniqueYesReturns FALSE if the form element is not unique to the table and field name in the +parameter. Note: This rule requires Query Builder to be +enabled in order to work.is_unique[table.field]
min_lengthYesReturns FALSE if the form element is shorter than the parameter value.min_length[3]
max_lengthYesReturns FALSE if the form element is longer than the parameter value.max_length[12]
exact_lengthYesReturns FALSE if the form element is not exactly the parameter value.exact_length[8]
greater_thanYesReturns FALSE if the form element is less than or equal to the parameter value or not +numeric.greater_than[8]
greater_than_equal_toYesReturns FALSE if the form element is less than the parameter value, +or not numeric.greater_than_equal_to[8]
less_thanYesReturns FALSE if the form element is greater than or equal to the parameter value or +not numeric.less_than[8]
less_than_equal_toYesReturns FALSE if the form element is greater than the parameter value, +or not numeric.less_than_equal_to[8]
in_listYesReturns FALSE if the form element is not within a predetermined list.in_list[red,blue,green]
alphaNoReturns FALSE if the form element contains anything other than alphabetical characters. 
alpha_numericNoReturns FALSE if the form element contains anything other than alpha-numeric characters. 
alpha_numeric_spacesNoReturns FALSE if the form element contains anything other than alpha-numeric characters +or spaces. Should be used after trim to avoid spaces at the beginning or end. 
alpha_dashNoReturns FALSE if the form element contains anything other than alpha-numeric characters, +underscores or dashes. 
numericNoReturns FALSE if the form element contains anything other than numeric characters. 
integerNoReturns FALSE if the form element contains anything other than an integer. 
decimalNoReturns FALSE if the form element contains anything other than a decimal number. 
is_naturalNoReturns FALSE if the form element contains anything other than a natural number: +0, 1, 2, 3, etc. 
is_natural_no_zeroNoReturns FALSE if the form element contains anything other than a natural +number, but not zero: 1, 2, 3, etc. 
valid_urlNoReturns FALSE if the form element does not contain a valid URL. 
valid_emailNoReturns FALSE if the form element does not contain a valid email address. 
valid_emailsNoReturns FALSE if any value provided in a comma separated list is not a valid email. 
valid_ipYesReturns FALSE if the supplied IP address is not valid. +Accepts an optional parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format. 
valid_base64NoReturns FALSE if the supplied string contains anything other than valid Base64 characters. 
+
+

Note

+

These rules can also be called as discrete methods. For +example:

+
$this->form_validation->required($string);
+
+
+
+
+

Note

+

You can also use any native PHP functions that permit up +to two parameters, where at least one is required (to pass +the field data).

+
+
+
+

Prepping Reference

+

The following is a list of all the prepping methods that are available +to use:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
NameParameterDescription
prep_for_formNoDEPRECATED: Converts special characters so that HTML data can be shown in a form field without breaking it.
prep_urlNoAdds “http://” to URLs if missing.
strip_image_tagsNoStrips the HTML from image tags leaving the raw URL.
encode_php_tagsNoConverts PHP tags to entities.
+
+

Note

+

You can also use any native PHP functions that permits one +parameter, like trim(), htmlspecialchars(), urldecode(), +etc.

+
+
+
+

Class Reference

+
+
+class CI_Form_validation
+
+
+set_rules($field[, $label = ''[, $rules = ''[, $errors = array()]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $field (string) – Field name
  • +
  • $label (string) – Field label
  • +
  • $rules (mixed) – Validation rules, as a string list separated by a pipe “|”, or as an array or rules
  • +
  • $errors (array) – A list of custom error messages
  • +
+
Returns:

CI_Form_validation instance (method chaining)

+
Return type:

CI_Form_validation

+
+

Permits you to set validation rules, as described in the tutorial +sections above:

+ +
+ +
+
+run([$group = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $group (string) – The name of the validation group to run
  • +
+
Returns:

TRUE on success, FALSE if validation failed

+
Return type:

bool

+
+

Runs the validation routines. Returns boolean TRUE on success and FALSE +on failure. You can optionally pass the name of the validation group via +the method, as described in: Saving Sets of Validation Rules to a Config File

+
+ +
+
+set_message($lang[, $val = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $lang (string) – The rule the message is for
  • +
  • $val (string) – The message
  • +
+
Returns:

CI_Form_validation instance (method chaining)

+
Return type:

CI_Form_validation

+
+

Permits you to set custom error messages. See Setting Error Messages

+
+ +
+
+set_error_delimiters([$prefix = '<p>'[, $suffix = '</p>']])
+
+++ + + + + + + + +
Parameters:
    +
  • $prefix (string) – Error message prefix
  • +
  • $suffix (string) – Error message suffix
  • +
+
Returns:

CI_Form_validation instance (method chaining)

+
Return type:

CI_Form_validation

+
+

Sets the default prefix and suffix for error messages.

+
+ +
+
+set_data($data)
+
+++ + + + + + + + +
Parameters:
    +
  • $data (array) – Array of data validate
  • +
+
Returns:

CI_Form_validation instance (method chaining)

+
Return type:

CI_Form_validation

+
+

Permits you to set an array for validation, instead of using the default +$_POST array.

+
+ +
+
+reset_validation()
+
+++ + + + + + +
Returns:CI_Form_validation instance (method chaining)
Return type:CI_Form_validation
+

Permits you to reset the validation when you validate more than one array. +This method should be called before validating each new array.

+
+ +
+
+error_array()
+
+++ + + + + + +
Returns:Array of error messages
Return type:array
+

Returns the error messages as an array.

+
+ +
+
+error_string([$prefix = ''[, $suffix = '']])
+
+++ + + + + + + + +
Parameters:
    +
  • $prefix (string) – Error message prefix
  • +
  • $suffix (string) – Error message suffix
  • +
+
Returns:

Error messages as a string

+
Return type:

string

+
+

Returns all error messages (as returned from error_array()) formatted as a +string and separated by a newline character.

+
+ +
+
+error($field[, $prefix = ''[, $suffix = '']])
+
+++ + + + + + + + +
Parameters:
    +
  • $field (string) – Field name
  • +
  • $prefix (string) – Optional prefix
  • +
  • $suffix (string) – Optional suffix
  • +
+
Returns:

Error message string

+
Return type:

string

+
+

Returns the error message for a specific field, optionally adding a +prefix and/or suffix to it (usually HTML tags).

+
+ +
+
+has_rule($field)
+
+++ + + + + + + + +
Parameters:
    +
  • $field (string) – Field name
  • +
+
Returns:

TRUE if the field has rules set, FALSE if not

+
Return type:

bool

+
+

Checks to see if there is a rule set for the specified field.

+
+ +
+ +
+
+

Helper Reference

+

Please refer to the Form Helper manual for +the following functions:

+ +

Note that these are procedural functions, so they do not require you +to prepend them with $this->form_validation.

+
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/ftp.html b/user_guide/libraries/ftp.html new file mode 100644 index 000000000..27d331231 --- /dev/null +++ b/user_guide/libraries/ftp.html @@ -0,0 +1,1016 @@ + + + + + + + + + + FTP Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

FTP Class

+

CodeIgniter’s FTP Class permits files to be transferred to a remote +server. Remote files can also be moved, renamed, and deleted. The FTP +class also includes a “mirroring” function that permits an entire local +directory to be recreated remotely via FTP.

+
+

Note

+

SFTP and SSL FTP protocols are not supported, only standard +FTP.

+
+ +
+

Working with the FTP Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the FTP class is initialized in +your controller using the $this->load->library function:

+
$this->load->library('ftp');
+
+
+

Once loaded, the FTP object will be available using: $this->ftp

+
+
+

Usage Examples

+

In this example a connection is opened to the FTP server, and a local +file is read and uploaded in ASCII mode. The file permissions are set to +755.

+
$this->load->library('ftp');
+
+$config['hostname'] = 'ftp.example.com';
+$config['username'] = 'your-username';
+$config['password'] = 'your-password';
+$config['debug']        = TRUE;
+
+$this->ftp->connect($config);
+
+$this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775);
+
+$this->ftp->close();
+
+
+

In this example a list of files is retrieved from the server.

+
$this->load->library('ftp');
+
+$config['hostname'] = 'ftp.example.com';
+$config['username'] = 'your-username';
+$config['password'] = 'your-password';
+$config['debug']        = TRUE;
+
+$this->ftp->connect($config);
+
+$list = $this->ftp->list_files('/public_html/');
+
+print_r($list);
+
+$this->ftp->close();
+
+
+

In this example a local directory is mirrored on the server.

+
$this->load->library('ftp');
+
+$config['hostname'] = 'ftp.example.com';
+$config['username'] = 'your-username';
+$config['password'] = 'your-password';
+$config['debug']        = TRUE;
+
+$this->ftp->connect($config);
+
+$this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/');
+
+$this->ftp->close();
+
+
+
+
+
+

Class Reference

+
+
+class CI_FTP
+
+
+connect([$config = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $config (array) – Connection values
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Connects and logs into to the FTP server. Connection preferences are set +by passing an array to the function, or you can store them in a config +file.

+

Here is an example showing how you set preferences manually:

+
$this->load->library('ftp');
+
+$config['hostname'] = 'ftp.example.com';
+$config['username'] = 'your-username';
+$config['password'] = 'your-password';
+$config['port']     = 21;
+$config['passive']  = FALSE;
+$config['debug']    = TRUE;
+
+$this->ftp->connect($config);
+
+
+

Setting FTP Preferences in a Config File

+

If you prefer you can store your FTP preferences in a config file. +Simply create a new file called the ftp.php, add the $config array in +that file. Then save the file at application/config/ftp.php and it +will be used automatically.

+

Available connection options

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Option nameDefault valueDescription
hostnamen/aFTP hostname (usually something like: ftp.example.com)
usernamen/aFTP username
passwordn/aFTP password
port21FTP server port number
debugFALSETRUE/FALSE (boolean): Whether to enable debugging to display error messages
passiveTRUETRUE/FALSE (boolean): Whether to use passive mode
+
+ +
+
+upload($locpath, $rempath[, $mode = 'auto'[, $permissions = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $locpath (string) – Local file path
  • +
  • $rempath (string) – Remote file path
  • +
  • $mode (string) – FTP mode, defaults to ‘auto’ (options are: ‘auto’, ‘binary’, ‘ascii’)
  • +
  • $permissions (int) – File permissions (octal)
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Uploads a file to your server. You must supply the local path and the +remote path, and you can optionally set the mode and permissions. +Example:

+
$this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775);
+
+
+

If ‘auto’ mode is used it will base the mode on the file extension of the source file.

+

If set, permissions have to be passed as an octal value.

+
+ +
+
+download($rempath, $locpath[, $mode = 'auto'])
+
+++ + + + + + + + +
Parameters:
    +
  • $rempath (string) – Remote file path
  • +
  • $locpath (string) – Local file path
  • +
  • $mode (string) – FTP mode, defaults to ‘auto’ (options are: ‘auto’, ‘binary’, ‘ascii’)
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Downloads a file from your server. You must supply the remote path and +the local path, and you can optionally set the mode. Example:

+
$this->ftp->download('/public_html/myfile.html', '/local/path/to/myfile.html', 'ascii');
+
+
+

If ‘auto’ mode is used it will base the mode on the file extension of the source file.

+

Returns FALSE if the download does not execute successfully +(including if PHP does not have permission to write the local file).

+
+ +
+
+rename($old_file, $new_file[, $move = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $old_file (string) – Old file name
  • +
  • $new_file (string) – New file name
  • +
  • $move (bool) – Whether a move is being performed
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Permits you to rename a file. Supply the source file name/path and the new file name/path.

+
// Renames green.html to blue.html
+$this->ftp->rename('/public_html/foo/green.html', '/public_html/foo/blue.html');
+
+
+
+ +
+
+move($old_file, $new_file)
+
+++ + + + + + + + +
Parameters:
    +
  • $old_file (string) – Old file name
  • +
  • $new_file (string) – New file name
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Lets you move a file. Supply the source and destination paths:

+
// Moves blog.html from "joe" to "fred"
+$this->ftp->move('/public_html/joe/blog.html', '/public_html/fred/blog.html');
+
+
+
+

Note

+

If the destination file name is different the file will be renamed.

+
+
+ +
+
+delete_file($filepath)
+
+++ + + + + + + + +
Parameters:
    +
  • $filepath (string) – Path to file to delete
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Lets you delete a file. Supply the source path with the file name.

+
$this->ftp->delete_file('/public_html/joe/blog.html');
+
+
+
+ +
+
+delete_dir($filepath)
+
+++ + + + + + + + +
Parameters:
    +
  • $filepath (string) – Path to directory to delete
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Lets you delete a directory and everything it contains. Supply the +source path to the directory with a trailing slash.

+
+

Important

+

Be VERY careful with this method! +It will recursively delete everything within the supplied path, +including sub-folders and all files. Make absolutely sure your path +is correct. Try using list_files() first to verify that your path is correct.

+
+
$this->ftp->delete_dir('/public_html/path/to/folder/');
+
+
+
+ +
+
+list_files([$path = '.'])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Directory path
  • +
+
Returns:

An array list of files or FALSE on failure

+
Return type:

array

+
+

Permits you to retrieve a list of files on your server returned as an +array. You must supply the path to the desired directory.

+
$list = $this->ftp->list_files('/public_html/');
+print_r($list);
+
+
+
+ +
+
+mirror($locpath, $rempath)
+
+++ + + + + + + + +
Parameters:
    +
  • $locpath (string) – Local path
  • +
  • $rempath (string) – Remote path
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Recursively reads a local folder and everything it contains (including +sub-folders) and creates a mirror via FTP based on it. Whatever the +directory structure of the original file path will be recreated on the +server. You must supply a source path and a destination path:

+
$this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/');
+
+
+
+ +
+
+mkdir($path[, $permissions = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Path to directory to create
  • +
  • $permissions (int) – Permissions (octal)
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Lets you create a directory on your server. Supply the path ending in +the folder name you wish to create, with a trailing slash.

+

Permissions can be set by passing an octal value in the second parameter.

+
// Creates a folder named "bar"
+$this->ftp->mkdir('/public_html/foo/bar/', 0755);
+
+
+
+ +
+
+chmod($path, $perm)
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Path to alter permissions for
  • +
  • $perm (int) – Permissions (octal)
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Permits you to set file permissions. Supply the path to the file or +directory you wish to alter permissions on:

+
// Chmod "bar" to 755
+$this->ftp->chmod('/public_html/foo/bar/', 0755);
+
+
+
+ +
+
+changedir($path[, $suppress_debug = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Directory path
  • +
  • $suppress_debug (bool) – Whether to turn off debug messages for this command
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Changes the current working directory to the specified path.

+

The $suppress_debug parameter is useful in case you want to use this method +as an is_dir() alternative for FTP.

+
+ +
+
+close()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

Closes the connection to your server. It’s recommended that you use this +when you are finished uploading.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/image_lib.html b/user_guide/libraries/image_lib.html new file mode 100644 index 000000000..3a9c2b597 --- /dev/null +++ b/user_guide/libraries/image_lib.html @@ -0,0 +1,1255 @@ + + + + + + + + + + Image Manipulation Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Image Manipulation Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Image Manipulation Class

+

CodeIgniter’s Image Manipulation class lets you perform the following +actions:

+
    +
  • Image Resizing
  • +
  • Thumbnail Creation
  • +
  • Image Cropping
  • +
  • Image Rotating
  • +
  • Image Watermarking
  • +
+

All three major image libraries are supported: GD/GD2, NetPBM, and +ImageMagick

+
+

Note

+

Watermarking is only available using the GD/GD2 library. In +addition, even though other libraries are supported, GD is required in +order for the script to calculate the image properties. The image +processing, however, will be performed with the library you specify.

+
+ +
+

Initializing the Class

+

Like most other classes in CodeIgniter, the image class is initialized +in your controller using the $this->load->library function:

+
$this->load->library('image_lib');
+
+
+

Once the library is loaded it will be ready for use. The image library +object you will use to call all functions is: $this->image_lib

+
+

Processing an Image

+

Regardless of the type of processing you would like to perform +(resizing, cropping, rotation, or watermarking), the general process is +identical. You will set some preferences corresponding to the action you +intend to perform, then call one of four available processing functions. +For example, to create an image thumbnail you’ll do this:

+
$config['image_library'] = 'gd2';
+$config['source_image'] = '/path/to/image/mypic.jpg';
+$config['create_thumb'] = TRUE;
+$config['maintain_ratio'] = TRUE;
+$config['width']         = 75;
+$config['height']       = 50;
+
+$this->load->library('image_lib', $config);
+
+$this->image_lib->resize();
+
+
+

The above code tells the image_resize function to look for an image +called mypic.jpg located in the source_image folder, then create a +thumbnail that is 75 X 50 pixels using the GD2 image_library. Since the +maintain_ratio option is enabled, the thumb will be as close to the +target width and height as possible while preserving the original aspect +ratio. The thumbnail will be called mypic_thumb.jpg and located at +the same level as source_image.

+
+

Note

+

In order for the image class to be allowed to do any +processing, the folder containing the image files must have write +permissions.

+
+
+

Note

+

Image processing can require a considerable amount of server +memory for some operations. If you are experiencing out of memory errors +while processing images you may need to limit their maximum size, and/or +adjust PHP memory limits.

+
+
+
+

Processing Methods

+

There are four available processing methods:

+
    +
  • $this->image_lib->resize()
  • +
  • $this->image_lib->crop()
  • +
  • $this->image_lib->rotate()
  • +
  • $this->image_lib->watermark()
  • +
+

These methods return boolean TRUE upon success and FALSE for failure. +If they fail you can retrieve the error message using this function:

+
echo $this->image_lib->display_errors();
+
+
+

A good practice is to use the processing function conditionally, showing an +error upon failure, like this:

+
if ( ! $this->image_lib->resize())
+{
+        echo $this->image_lib->display_errors();
+}
+
+
+
+

Note

+

You can optionally specify the HTML formatting to be applied to +the errors, by submitting the opening/closing tags in the function, +like this:

+
$this->image_lib->display_errors('<p>', '</p>');
+
+
+
+
+
+

Preferences

+

The preferences described below allow you to tailor the image processing +to suit your needs.

+

Note that not all preferences are available for every function. For +example, the x/y axis preferences are only available for image cropping. +Likewise, the width and height preferences have no effect on cropping. +The “availability” column indicates which functions support a given +preference.

+

Availability Legend:

+
    +
  • R - Image Resizing
  • +
  • C - Image Cropping
  • +
  • X - Image Rotation
  • +
  • W - Image Watermarking
  • +
+ +++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescriptionAvailability
image_libraryGD2GD, GD2, ImageMagick, NetPBMSets the image library to be used.R, C, X, W
library_pathNoneNoneSets the server path to your ImageMagick or NetPBM library. If you use +either of those libraries you must supply the path.R, C, X +R, C, S, W
source_imageNoneNoneSets the source image name/path. The path must be a relative or absolute +server path, not a URL. 
dynamic_outputFALSETRUE/FALSE (boolean)Determines whether the new image file should be written to disk or +generated dynamically. Note: If you choose the dynamic setting, only one +image can be shown at a time, and it can’t be positioned on the page. It +simply outputs the raw image dynamically to your browser, along with +image headers.R, C, X, W
file_permissions0644(integer)File system permissions to apply on the resulting image file, +writing it to the disk. WARNING: Use octal integer notation!R, C, X, W
quality90%1 - 100%Sets the quality of the image. The higher the quality the larger the +file size.R, C, X, W
new_imageNoneNoneSets the destination image name/path. You’ll use this preference when +creating an image copy. The path must be a relative or absolute server +path, not a URL.R, C, X, W
widthNoneNoneSets the width you would like the image set to.R, C
heightNoneNoneSets the height you would like the image set to.R, C
create_thumbFALSETRUE/FALSE (boolean)Tells the image processing function to create a thumb.R
thumb_marker_thumbNoneSpecifies the thumbnail indicator. It will be inserted just before the +file extension, so mypic.jpg would become mypic_thumb.jpgR
maintain_ratioTRUETRUE/FALSE (boolean)Specifies whether to maintain the original aspect ratio when resizing or +use hard values.R, C
master_dimautoauto, width, heightSpecifies what to use as the master axis when resizing or creating +thumbs. For example, let’s say you want to resize an image to 100 X 75 +pixels. If the source image size does not allow perfect resizing to +those dimensions, this setting determines which axis should be used as +the hard value. “auto” sets the axis automatically based on whether the +image is taller than wider, or vice versa.R
rotation_angleNone90, 180, 270, vrt, horSpecifies the angle of rotation when rotating images. Note that PHP +rotates counter-clockwise, so a 90 degree rotation to the right must be +specified as 270.X
x_axisNoneNoneSets the X coordinate in pixels for image cropping. For example, a +setting of 30 will crop an image 30 pixels from the left.C
y_axisNoneNoneSets the Y coordinate in pixels for image cropping. For example, a +setting of 30 will crop an image 30 pixels from the top.C
+
+
+

Setting preferences in a config file

+

If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called +image_lib.php, add the $config array in that file. Then save the file +in config/image_lib.php and it will be used automatically. You will +NOT need to use the $this->image_lib->initialize() method if you save +your preferences in a config file.

+
+
+
+

Image Watermarking

+

The Watermarking feature requires the GD/GD2 library.

+
+

Two Types of Watermarking

+

There are two types of watermarking that you can use:

+
    +
  • Text: The watermark message will be generated using text, either +with a True Type font that you specify, or using the native text +output that the GD library supports. If you use the True Type version +your GD installation must be compiled with True Type support (most +are, but not all).
  • +
  • Overlay: The watermark message will be generated by overlaying an +image (usually a transparent PNG or GIF) containing your watermark +over the source image.
  • +
+
+
+

Watermarking an Image

+

Just as with the other methods (resizing, cropping, and rotating) the +general process for watermarking involves setting the preferences +corresponding to the action you intend to perform, then calling the +watermark function. Here is an example:

+
$config['source_image'] = '/path/to/image/mypic.jpg';
+$config['wm_text'] = 'Copyright 2006 - John Doe';
+$config['wm_type'] = 'text';
+$config['wm_font_path'] = './system/fonts/texb.ttf';
+$config['wm_font_size'] = '16';
+$config['wm_font_color'] = 'ffffff';
+$config['wm_vrt_alignment'] = 'bottom';
+$config['wm_hor_alignment'] = 'center';
+$config['wm_padding'] = '20';
+
+$this->image_lib->initialize($config);
+
+$this->image_lib->watermark();
+
+
+

The above example will use a 16 pixel True Type font to create the text +“Copyright 2006 - John Doe”. The watermark will be positioned at the +bottom/center of the image, 20 pixels from the bottom of the image.

+
+

Note

+

In order for the image class to be allowed to do any +processing, the image file must have “write” file permissions +For example, 777.

+
+
+
+

Watermarking Preferences

+

This table shows the preferences that are available for both types of +watermarking (text or overlay)

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
wm_typetexttext, overlaySets the type of watermarking that should be used.
source_imageNoneNoneSets the source image name/path. The path must be a relative or absolute +server path, not a URL.
dynamic_outputFALSETRUE/FALSE (boolean)Determines whether the new image file should be written to disk or +generated dynamically. Note: If you choose the dynamic setting, only one +image can be shown at a time, and it can’t be positioned on the page. It +simply outputs the raw image dynamically to your browser, along with +image headers.
quality90%1 - 100%Sets the quality of the image. The higher the quality the larger the +file size.
wm_paddingNoneA numberThe amount of padding, set in pixels, that will be applied to the +watermark to set it away from the edge of your images.
wm_vrt_alignmentbottomtop, middle, bottomSets the vertical alignment for the watermark image.
wm_hor_alignmentcenterleft, center, rightSets the horizontal alignment for the watermark image.
wm_hor_offsetNoneNoneYou may specify a horizontal offset (in pixels) to apply to the +watermark position. The offset normally moves the watermark to the +right, except if you have your alignment set to “right” then your offset +value will move the watermark toward the left of the image.
wm_vrt_offsetNoneNoneYou may specify a vertical offset (in pixels) to apply to the watermark +position. The offset normally moves the watermark down, except if you +have your alignment set to “bottom” then your offset value will move the +watermark toward the top of the image.
+
+

Text Preferences

+

This table shows the preferences that are available for the text type of +watermarking.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
wm_textNoneNoneThe text you would like shown as the watermark. Typically this will be a +copyright notice.
wm_font_pathNoneNoneThe server path to the True Type Font you would like to use. If you do +not use this option, the native GD font will be used.
wm_font_size16NoneThe size of the text. Note: If you are not using the True Type option +above, the number is set using a range of 1 - 5. Otherwise, you can use +any valid pixel size for the font you’re using.
wm_font_colorffffffNoneThe font color, specified in hex. Both the full 6-length (ie, 993300) and +the short three character abbreviated version (ie, fff) are supported.
wm_shadow_colorNoneNoneThe color of the drop shadow, specified in hex. If you leave this blank +a drop shadow will not be used. Both the full 6-length (ie, 993300) and +the short three character abbreviated version (ie, fff) are supported.
wm_shadow_distance3NoneThe distance (in pixels) from the font that the drop shadow should +appear.
+
+
+

Overlay Preferences

+

This table shows the preferences that are available for the overlay type +of watermarking.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
wm_overlay_pathNoneNoneThe server path to the image you wish to use as your watermark. Required +only if you are using the overlay method.
wm_opacity501 - 100Image opacity. You may specify the opacity (i.e. transparency) of your +watermark image. This allows the watermark to be faint and not +completely obscure the details from the original image behind it. A 50% +opacity is typical.
wm_x_transp4A numberIf your watermark image is a PNG or GIF image, you may specify a color +on the image to be “transparent”. This setting (along with the next) +will allow you to specify that color. This works by specifying the “X” +and “Y” coordinate pixel (measured from the upper left) within the image +that corresponds to a pixel representative of the color you want to be +transparent.
wm_y_transp4A numberAlong with the previous setting, this allows you to specify the +coordinate to a pixel representative of the color you want to be +transparent.
+
+
+
+
+

Class Reference

+
+
+class CI_Image_lib
+
+
+initialize([$props = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $props (array) – Image processing preferences
  • +
+
Returns:

TRUE on success, FALSE in case of invalid settings

+
Return type:

bool

+
+

Initializes the class for processing an image.

+
+ +
+
+resize()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

The image resizing method lets you resize the original image, create a +copy (with or without resizing), or create a thumbnail image.

+

For practical purposes there is no difference between creating a copy +and creating a thumbnail except a thumb will have the thumbnail marker +as part of the name (i.e. mypic_thumb.jpg).

+

All preferences listed in the Preferences table are available for this +method except these three: rotation_angle, x_axis and y_axis.

+

Creating a Thumbnail

+

The resizing method will create a thumbnail file (and preserve the +original) if you set this preference to TRUE:

+
$config['create_thumb'] = TRUE;
+
+
+

This single preference determines whether a thumbnail is created or not.

+

Creating a Copy

+

The resizing method will create a copy of the image file (and preserve +the original) if you set a path and/or a new filename using this +preference:

+
$config['new_image'] = '/path/to/new_image.jpg';
+
+
+

Notes regarding this preference:

+
    +
  • If only the new image name is specified it will be placed in the same +folder as the original
  • +
  • If only the path is specified, the new image will be placed in the +destination with the same name as the original.
  • +
  • If both the path and image name are specified it will placed in its +own destination and given the new name.
  • +
+

Resizing the Original Image

+

If neither of the two preferences listed above (create_thumb, and +new_image) are used, the resizing method will instead target the +original image for processing.

+
+ +
+
+crop()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

The cropping method works nearly identically to the resizing function +except it requires that you set preferences for the X and Y axis (in +pixels) specifying where to crop, like this:

+
$config['x_axis'] = 100;
+$config['y_axis'] = 40;
+
+
+

All preferences listed in the Preferences table are available for this +method except these: rotation_angle, create_thumb and new_image.

+

Here’s an example showing how you might crop an image:

+
$config['image_library'] = 'imagemagick';
+$config['library_path'] = '/usr/X11R6/bin/';
+$config['source_image'] = '/path/to/image/mypic.jpg';
+$config['x_axis'] = 100;
+$config['y_axis'] = 60;
+
+$this->image_lib->initialize($config);
+
+if ( ! $this->image_lib->crop())
+{
+        echo $this->image_lib->display_errors();
+}
+
+
+
+

Note

+

Without a visual interface it is difficult to crop images, so this +method is not very useful unless you intend to build such an +interface. That’s exactly what we did using for the photo gallery module +in ExpressionEngine, the CMS we develop. We added a JavaScript UI that +lets the cropping area be selected.

+
+
+ +
+
+rotate()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

The image rotation method requires that the angle of rotation be set +via its preference:

+
$config['rotation_angle'] = '90';
+
+
+

There are 5 rotation options:

+
    +
  1. 90 - rotates counter-clockwise by 90 degrees.
  2. +
  3. 180 - rotates counter-clockwise by 180 degrees.
  4. +
  5. 270 - rotates counter-clockwise by 270 degrees.
  6. +
  7. hor - flips the image horizontally.
  8. +
  9. vrt - flips the image vertically.
  10. +
+

Here’s an example showing how you might rotate an image:

+
$config['image_library'] = 'netpbm';
+$config['library_path'] = '/usr/bin/';
+$config['source_image'] = '/path/to/image/mypic.jpg';
+$config['rotation_angle'] = 'hor';
+
+$this->image_lib->initialize($config);
+
+if ( ! $this->image_lib->rotate())
+{
+        echo $this->image_lib->display_errors();
+}
+
+
+
+ +
+
+watermark()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

Creates a watermark over an image, please refer to the Watermarking an Image +section for more info.

+
+ +
+
+clear()
+
+++ + + + +
Return type:void
+

The clear method resets all of the values used when processing an +image. You will want to call this if you are processing images in a +loop.

+
$this->image_lib->clear();
+
+
+
+ +
+
+display_errors([$open = '<p>[, $close = '</p>']])
+
+++ + + + + + + + +
Parameters:
    +
  • $open (string) – Error message opening tag
  • +
  • $close (string) – Error message closing tag
  • +
+
Returns:

Error messages

+
Return type:

string

+
+

Returns all detected errors formatted as a string.

+
echo $this->image_lib->display_errors();
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/index.html b/user_guide/libraries/index.html new file mode 100644 index 000000000..79f650779 --- /dev/null +++ b/user_guide/libraries/index.html @@ -0,0 +1,527 @@ + + + + + + + + + + Libraries — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/input.html b/user_guide/libraries/input.html new file mode 100644 index 000000000..34b9a7ff4 --- /dev/null +++ b/user_guide/libraries/input.html @@ -0,0 +1,1191 @@ + + + + + + + + + + Input Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Input Class

+

The Input Class serves two purposes:

+
    +
  1. It pre-processes global input data for security.
  2. +
  3. It provides some helper methods for fetching input data and pre-processing it.
  4. +
+
+

Note

+

This class is initialized automatically by the system so there +is no need to do it manually.

+
+ +
+

Input Filtering

+
+

Security Filtering

+

The security filtering method is called automatically when a new +controller is invoked. It does the +following:

+
    +
  • If $config['allow_get_array'] is FALSE (default is TRUE), destroys +the global GET array.
  • +
  • Destroys all global variables in the event register_globals is +turned on.
  • +
  • Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric +(and a few other) characters.
  • +
  • Provides XSS (Cross-site Scripting Hacks) filtering. This can be +enabled globally, or upon request.
  • +
  • Standardizes newline characters to PHP_EOL (\n in UNIX-based OSes, +\r\n under Windows). This is configurable.
  • +
+
+
+

XSS Filtering

+

The Input class has the ability to filter input automatically to prevent +cross-site scripting attacks. If you want the filter to run +automatically every time it encounters POST or COOKIE data you can +enable it by opening your application/config/config.php file and setting +this:

+
$config['global_xss_filtering'] = TRUE;
+
+
+

Please refer to the Security class documentation for +information on using XSS Filtering in your application.

+
+

Important

+

The ‘global_xss_filtering’ setting is DEPRECATED and kept +solely for backwards-compatibility purposes. XSS escaping should +be performed on output, not input!

+
+
+
+
+

Accessing form data

+
+

Using POST, GET, COOKIE, or SERVER Data

+

CodeIgniter comes with helper methods that let you fetch POST, GET, +COOKIE or SERVER items. The main advantage of using the provided +methods rather than fetching an item directly ($_POST['something']) +is that the methods will check to see if the item is set and return +NULL if not. This lets you conveniently use data without +having to test whether an item exists first. In other words, normally +you might do something like this:

+
$something = isset($_POST['something']) ? $_POST['something'] : NULL;
+
+
+

With CodeIgniter’s built in methods you can simply do this:

+
$something = $this->input->post('something');
+
+
+

The main methods are:

+
    +
  • $this->input->post()
  • +
  • $this->input->get()
  • +
  • $this->input->cookie()
  • +
  • $this->input->server()
  • +
+
+
+

Using the php://input stream

+

If you want to utilize the PUT, DELETE, PATCH or other exotic request +methods, they can only be accessed via a special input stream, that +can only be read once. This isn’t as easy as just reading from e.g. +the $_POST array, because it will always exist and you can try +and access multiple variables without caring that you might only have +one shot at all of the POST data.

+

CodeIgniter will take care of that for you, and you can read the data +from the php://input stream at any time, just by using the +$raw_input_stream property:

+
$this->input->raw_input_stream;
+
+
+

Additionally if the input stream is form-encoded like $_POST you can +access its values by calling the +input_stream() method:

+
$this->input->input_stream('key');
+
+
+

Similar to other methods such as get() and post(), if the +requested data is not found, it will return NULL and you can also +decide whether to run the data through xss_clean() by passing +a boolean value as the second parameter:

+
$this->input->input_stream('key', TRUE); // XSS Clean
+$this->input->input_stream('key', FALSE); // No XSS filter
+
+
+
+

Note

+

You can utilize method() in order to know if you’re reading +PUT, DELETE or PATCH data.

+
+
+
+
+

Class Reference

+
+
+class CI_Input
+
+
+$raw_input_stream
+

Read only property that will return php://input data as is.

+

The property can be read multiple times.

+
+ +
+
+post([$index = NULL[, $xss_clean = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (mixed) – POST parameter name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

$_POST if no parameters supplied, otherwise the POST value if found or NULL if not

+
Return type:

mixed

+
+

The first parameter will contain the name of the POST item you are +looking for:

+
$this->input->post('some_data');
+
+
+

The method returns NULL if the item you are attempting to retrieve +does not exist.

+

The second optional parameter lets you run the data through the XSS +filter. It’s enabled by setting the second parameter to boolean TRUE +or by setting your $config['global_xss_filtering'] to TRUE.

+
$this->input->post('some_data', TRUE);
+
+
+

To return an array of all POST items call without any parameters.

+

To return all POST items and pass them through the XSS filter set the +first parameter NULL while setting the second parameter to boolean TRUE.

+
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
+$this->input->post(NULL, FALSE); // returns all POST items without XSS filter
+
+
+

To return an array of multiple POST parameters, pass all the required keys +as an array.

+
$this->input->post(array('field1', 'field2'));
+
+
+

Same rule applied here, to retrieve the parameters with XSS filtering enabled, set the +second parameter to boolean TRUE.

+
$this->input->post(array('field1', 'field2'), TRUE);
+
+
+
+ +
+
+get([$index = NULL[, $xss_clean = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (mixed) – GET parameter name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

$_GET if no parameters supplied, otherwise the GET value if found or NULL if not

+
Return type:

mixed

+
+

This method is identical to post(), only it fetches GET data.

+
$this->input->get('some_data', TRUE);
+
+
+

To return an array of all GET items call without any parameters.

+

To return all GET items and pass them through the XSS filter set the +first parameter NULL while setting the second parameter to boolean TRUE.

+
$this->input->get(NULL, TRUE); // returns all GET items with XSS filter
+$this->input->get(NULL, FALSE); // returns all GET items without XSS filtering
+
+
+

To return an array of multiple GET parameters, pass all the required keys +as an array.

+
$this->input->get(array('field1', 'field2'));
+
+
+

Same rule applied here, to retrieve the parameters with XSS filtering enabled, set the +second parameter to boolean TRUE.

+
$this->input->get(array('field1', 'field2'), TRUE);
+
+
+
+ +
+
+post_get($index[, $xss_clean = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (string) – POST/GET parameter name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

POST/GET value if found, NULL if not

+
Return type:

mixed

+
+

This method works pretty much the same way as post() and get(), +only combined. It will search through both POST and GET streams for data, +looking in POST first, and then in GET:

+
$this->input->post_get('some_data', TRUE);
+
+
+
+ +
+
+get_post($index[, $xss_clean = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (string) – GET/POST parameter name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

GET/POST value if found, NULL if not

+
Return type:

mixed

+
+

This method works the same way as post_get() only it looks for GET +data first.

+
+
$this->input->get_post(‘some_data’, TRUE);
+
+

Note

+

This method used to act EXACTLY like post_get(), but it’s +behavior has changed in CodeIgniter 3.0.

+
+
+ +
+
+cookie([$index = NULL[, $xss_clean = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (mixed) – COOKIE name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

$_COOKIE if no parameters supplied, otherwise the COOKIE value if found or NULL if not

+
Return type:

mixed

+
+

This method is identical to post() and get(), only it fetches cookie +data:

+
$this->input->cookie('some_cookie');
+$this->input->cookie('some_cookie', TRUE); // with XSS filter
+
+
+

To return an array of multiple cookie values, pass all the required keys +as an array.

+
$this->input->cookie(array('some_cookie', 'some_cookie2'));
+
+
+
+

Note

+

Unlike the Cookie Helper +function get_cookie(), this method does NOT prepend +your configured $config['cookie_prefix'] value.

+
+
+ +
+
+server($index[, $xss_clean = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (mixed) – Value name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

$_SERVER item value if found, NULL if not

+
Return type:

mixed

+
+

This method is identical to the post(), get() and cookie() +methods, only it fetches server data ($_SERVER):

+
$this->input->server('some_data');
+
+
+

To return an array of multiple $_SERVER values, pass all the required keys +as an array.

+
$this->input->server(array('SERVER_PROTOCOL', 'REQUEST_URI'));
+
+
+
+ +
+
+input_stream([$index = NULL[, $xss_clean = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (mixed) – Key name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

Input stream array if no parameters supplied, otherwise the specified value if found or NULL if not

+
Return type:

mixed

+
+

This method is identical to get(), post() and cookie(), +only it fetches the php://input stream data.

+
+ +
+ +
+++ + + + + + +
Parameters:
    +
  • $name (mixed) – Cookie name or an array of parameters
  • +
  • $value (string) – Cookie value
  • +
  • $expire (int) – Cookie expiration time in seconds
  • +
  • $domain (string) – Cookie domain
  • +
  • $path (string) – Cookie path
  • +
  • $prefix (string) – Cookie name prefix
  • +
  • $secure (bool) – Whether to only transfer the cookie through HTTPS
  • +
  • $httponly (bool) – Whether to only make the cookie accessible for HTTP requests (no JavaScript)
  • +
+
Return type:

void

+
+

Sets a cookie containing the values you specify. There are two ways to +pass information to this method so that a cookie can be set: Array +Method, and Discrete Parameters:

+

Array Method

+

Using this method, an associative array is passed to the first +parameter:

+
$cookie = array(
+        'name'   => 'The Cookie Name',
+        'value'  => 'The Value',
+        'expire' => '86500',
+        'domain' => '.some-domain.com',
+        'path'   => '/',
+        'prefix' => 'myprefix_',
+        'secure' => TRUE
+);
+
+$this->input->set_cookie($cookie);
+
+
+

Notes

+

Only the name and value are required. To delete a cookie set it with the +expiration blank.

+

The expiration is set in seconds, which will be added to the current +time. Do not include the time, but rather only the number of seconds +from now that you wish the cookie to be valid. If the expiration is +set to zero the cookie will only last as long as the browser is open.

+

For site-wide cookies regardless of how your site is requested, add your +URL to the domain starting with a period, like this: +.your-domain.com

+

The path is usually not needed since the method sets a root path.

+

The prefix is only needed if you need to avoid name collisions with +other identically named cookies for your server.

+

The httponly and secure flags, when omitted, will default to your +$config['cookie_httponly'] and $config['cookie_secure'] settings.

+

Discrete Parameters

+

If you prefer, you can set the cookie by passing data using individual +parameters:

+
$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);
+
+
+
+ +
+
+ip_address()
+
+++ + + + + + +
Returns:Visitor’s IP address or ‘0.0.0.0’ if not valid
Return type:string
+

Returns the IP address for the current user. If the IP address is not +valid, the method will return ‘0.0.0.0’:

+
echo $this->input->ip_address();
+
+
+
+

Important

+

This method takes into account the $config['proxy_ips'] +setting and will return the reported HTTP_X_FORWARDED_FOR, +HTTP_CLIENT_IP, HTTP_X_CLIENT_IP or HTTP_X_CLUSTER_CLIENT_IP +address for the allowed IP addresses.

+
+
+ +
+
+valid_ip($ip[, $which = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $ip (string) – IP address
  • +
  • $which (string) – IP protocol (‘ipv4’ or ‘ipv6’)
  • +
+
Returns:

TRUE if the address is valid, FALSE if not

+
Return type:

bool

+
+

Takes an IP address as input and returns TRUE or FALSE (boolean) depending +on whether it is valid or not.

+
+

Note

+

The $this->input->ip_address() method above automatically +validates the IP address.

+
+
if ( ! $this->input->valid_ip($ip))
+{
+        echo 'Not Valid';
+}
+else
+{
+        echo 'Valid';
+}
+
+
+

Accepts an optional second string parameter of ‘ipv4’ or ‘ipv6’ to specify +an IP format. The default checks for both formats.

+
+ +
+
+user_agent([$xss_clean = NULL])
+
+++ + + + + + + + +
Returns:

User agent string or NULL if not set

+
Parameters:
    +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Return type:

mixed

+
+

Returns the user agent string (web browser) being used by the current user, +or NULL if it’s not available.

+
echo $this->input->user_agent();
+
+
+

See the User Agent Class for methods which extract +information from the user agent string.

+
+ +
+
+request_headers([$xss_clean = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

An array of HTTP request headers

+
Return type:

array

+
+

Returns an array of HTTP request headers. +Useful if running in a non-Apache environment where +apache_request_headers() +will not be supported.

+
$headers = $this->input->request_headers();
+
+
+
+ +
+
+get_request_header($index[, $xss_clean = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $index (string) – HTTP request header name
  • +
  • $xss_clean (bool) – Whether to apply XSS filtering
  • +
+
Returns:

An HTTP request header or NULL if not found

+
Return type:

string

+
+

Returns a single member of the request headers array or NULL +if the searched header is not found.

+
$this->input->get_request_header('some-header', TRUE);
+
+
+
+ +
+
+is_ajax_request()
+
+++ + + + + + +
Returns:TRUE if it is an Ajax request, FALSE if not
Return type:bool
+

Checks to see if the HTTP_X_REQUESTED_WITH server header has been +set, and returns boolean TRUE if it is or FALSE if not.

+
+ +
+
+is_cli_request()
+
+++ + + + + + +
Returns:TRUE if it is a CLI request, FALSE if not
Return type:bool
+

Checks to see if the application was run from the command-line +interface.

+
+

Note

+

This method checks both the PHP SAPI name currently in use +and if the STDIN constant is defined, which is usually a +failsafe way to see if PHP is being run via the command line.

+
+
$this->input->is_cli_request()
+
+
+
+

Note

+

This method is DEPRECATED and is now just an alias for the +is_cli() function.

+
+
+ +
+
+method([$upper = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $upper (bool) – Whether to return the request method name in upper or lower case
  • +
+
Returns:

HTTP request method

+
Return type:

string

+
+

Returns the $_SERVER['REQUEST_METHOD'], with the option to set it +in uppercase or lowercase.

+
echo $this->input->method(TRUE); // Outputs: POST
+echo $this->input->method(FALSE); // Outputs: post
+echo $this->input->method(); // Outputs: post
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/javascript.html b/user_guide/libraries/javascript.html new file mode 100644 index 000000000..5f1e1e242 --- /dev/null +++ b/user_guide/libraries/javascript.html @@ -0,0 +1,802 @@ + + + + + + + + + + Javascript Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Javascript Class

+

CodeIgniter provides a library to help you with certain common functions +that you may want to use with Javascript. Please note that CodeIgniter +does not require the jQuery library to run, and that any scripting +library will work equally well. The jQuery library is simply presented +as a convenience if you choose to use it.

+
+

Important

+

This library is DEPRECATED and should not be used. It has always +been with an ‘experimental’ status and is now no longer supported. +Currently only kept for backwards compatibility.

+
+ +
+

Using the Javascript Class

+
+

Initializing the Class

+

To initialize the Javascript class manually in your controller +constructor, use the $this->load->library() method. Currently, +the only available library is jQuery, which will automatically be +loaded like this:

+
$this->load->library('javascript');
+
+
+

The Javascript class also accepts parameters:

+
    +
  • js_library_driver (string) default: ‘jquery’
  • +
  • autoload (bool) default: TRUE
  • +
+

You may override the defaults by sending an associative array:

+
$this->load->library(
+        'javascript',
+        array(
+                'js_library_driver' => 'scripto',
+                'autoload' => FALSE
+        )
+);
+
+
+

Again, presently only ‘jquery’ is available. You may wish to set +autoload to FALSE, though, if you do not want the jQuery library to +automatically include a script tag for the main jQuery script file. This +is useful if you are loading it from a location outside of CodeIgniter, +or already have the script tag in your markup.

+

Once loaded, the jQuery library object will be available using:

+
+
$this->javascript
+
+
+

Setup and Configuration

+
+

Set these variables in your view

+

As a Javascript library, your files must be available to your +application.

+

As Javascript is a client side language, the library must be able to +write content into your final output. This generally means a view. +You’ll need to include the following variables in the <head> +sections of your output.

+
<?php echo $library_src;?>
+<?php echo $script_head;?>
+
+
+

$library_src, is where the actual library file will be loaded, as +well as any subsequent plugin script calls; $script_head is where +specific events, functions and other commands will be rendered.

+
+
+

Set the path to the librarys with config items

+

There are some configuration items in Javascript library. These can +either be set in application/config.php, within its own +config/javascript.php file, or within any controller usings the +set_item() function.

+

An image to be used as an “ajax loader”, or progress indicator. Without +one, the simple text message of “loading” will appear when Ajax calls +need to be made.

+
$config['javascript_location'] = 'http://localhost/codeigniter/themes/js/jquery/';
+$config['javascript_ajax_img'] = 'images/ajax-loader.gif';
+
+
+

If you keep your files in the same directories they were downloaded +from, then you need not set this configuration items.

+
+
+
+

The jQuery Class

+

To initialize the jQuery class manually in your controller constructor, +use the $this->load->library() method:

+
$this->load->library('javascript/jquery');
+
+
+

You may send an optional parameter to determine whether or not a script +tag for the main jQuery file will be automatically included when loading +the library. It will be created by default. To prevent this, load the +library as follows:

+
$this->load->library('javascript/jquery', FALSE);
+
+
+

Once loaded, the jQuery library object will be available using:

+
+
$this->jquery
+
+
+

jQuery Events

+

Events are set using the following syntax.

+
$this->jquery->event('element_path', code_to_run());
+
+
+

In the above example:

+
    +
  • “event” is any of blur, change, click, dblclick, error, focus, hover, +keydown, keyup, load, mousedown, mouseup, mouseover, mouseup, resize, +scroll, or unload.
  • +
  • “element_path” is any valid jQuery selector. Due to jQuery’s unique +selector syntax, this is usually an element id, or CSS selector. For +example “#notice_area” would effect <div id="notice_area">, and +“#content a.notice” would effect all anchors with a class of “notice” +in the div with id “content”.
  • +
  • code_to_run()” is script your write yourself, or an action such as +an effect from the jQuery library below.
  • +
+
+
+

Effects

+

The query library supports a powerful +Effects repertoire. Before an effect +can be used, it must be loaded:

+
$this->jquery->effect([optional path] plugin name); // for example $this->jquery->effect('bounce');
+
+
+
+

hide() / show()

+

Each of this functions will affect the visibility of an item on your +page. hide() will set an item invisible, show() will reveal it.

+
$this->jquery->hide(target, optional speed, optional extra information);
+$this->jquery->show(target, optional speed, optional extra information);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “speed” is optional, and is set to either slow, normal, fast, or +alternatively a number of milliseconds.
  • +
  • “extra information” is optional, and could include a callback, or +other additional information.
  • +
+
+
+

toggle()

+

toggle() will change the visibility of an item to the opposite of its +current state, hiding visible elements, and revealing hidden ones.

+
$this->jquery->toggle(target);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
+
+
+

animate()

+
$this->jquery->animate(target, parameters, optional speed, optional extra information);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “parameters” in jQuery would generally include a series of CSS +properties that you wish to change.
  • +
  • “speed” is optional, and is set to either slow, normal, fast, or +alternatively a number of milliseconds.
  • +
  • “extra information” is optional, and could include a callback, or +other additional information.
  • +
+

For a full summary, see +http://api.jquery.com/animate/

+

Here is an example of an animate() called on a div with an id of “note”, +and triggered by a click using the jQuery library’s click() event.

+
$params = array(
+'height' => 80,
+'width' => '50%',
+'marginLeft' => 125
+);
+$this->jquery->click('#trigger', $this->jquery->animate('#note', $params, 'normal'));
+
+
+
+
+

fadeIn() / fadeOut()

+
$this->jquery->fadeIn(target,  optional speed, optional extra information);
+$this->jquery->fadeOut(target,  optional speed, optional extra information);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “speed” is optional, and is set to either slow, normal, fast, or +alternatively a number of milliseconds.
  • +
  • “extra information” is optional, and could include a callback, or +other additional information.
  • +
+
+
+

toggleClass()

+

This function will add or remove a CSS class to its target.

+
$this->jquery->toggleClass(target, class)
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “class” is any CSS classname. Note that this class must be defined +and available in a CSS that is already loaded.
  • +
+
+
+

fadeIn() / fadeOut()

+

These effects cause an element(s) to disappear or reappear over time.

+
$this->jquery->fadeIn(target,  optional speed, optional extra information);
+$this->jquery->fadeOut(target,  optional speed, optional extra information);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “speed” is optional, and is set to either slow, normal, fast, or +alternatively a number of milliseconds.
  • +
  • “extra information” is optional, and could include a callback, or +other additional information.
  • +
+
+
+

slideUp() / slideDown() / slideToggle()

+

These effects cause an element(s) to slide.

+
$this->jquery->slideUp(target,  optional speed, optional extra information);
+$this->jquery->slideDown(target,  optional speed, optional extra information);
+$this->jquery->slideToggle(target,  optional speed, optional extra information);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “speed” is optional, and is set to either slow, normal, fast, or +alternatively a number of milliseconds.
  • +
  • “extra information” is optional, and could include a callback, or +other additional information.
  • +
+
+
+
+

Plugins

+

Some select jQuery plugins are made available using this library.

+
+

corner()

+

Used to add distinct corners to page elements. For full details see +http://malsup.com/jquery/corner/

+
$this->jquery->corner(target, corner_style);
+
+
+
    +
  • “target” will be any valid jQuery selector or selectors.
  • +
  • “corner_style” is optional, and can be set to any valid style such +as round, sharp, bevel, bite, dog, etc. Individual corners can be set +by following the style with a space and using “tl” (top left), “tr” +(top right), “bl” (bottom left), or “br” (bottom right).
  • +
+
$this->jquery->corner("#note", "cool tl br");
+
+
+
+
+

tablesorter()

+

description to come

+
+ +
+

calendar()

+

description to come

+
+
+
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/language.html b/user_guide/libraries/language.html new file mode 100644 index 000000000..c2e8781b9 --- /dev/null +++ b/user_guide/libraries/language.html @@ -0,0 +1,733 @@ + + + + + + + + + + Language Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Language Class

+

The Language Class provides functions to retrieve language files and +lines of text for purposes of internationalization.

+

In your CodeIgniter system folder, you will find a language sub-directory +containing a set of language files for the english idiom. +The files in this directory (system/language/english/) define the regular messages, +error messages, and other generally output terms or expressions, for the different parts +of the CodeIgniter framework.

+

You can create or incorporate your own language files, as needed, in order to provide +application-specific error and other messages, or to provide translations of the core +messages into other languages. These translations or additional messages would go inside +your application/language/ directory, with separate sub-directories for each idiom +(for instance, ‘french’ or ‘german’).

+

The CodeIgniter framework comes with a set of language files for the “english” idiom. +Additional approved translations for different idioms may be found in the +CodeIgniter 3 Translations repositories. +Each repository deals with a single idiom.

+

When CodeIgniter loads language files, it will load the one in system/language/ +first and will then look for an override in your application/language/ directory.

+
+

Note

+

Each language should be stored in its own folder. For example, +the English files are located at: system/language/english

+
+ +
+

Handling Multiple Languages

+

If you want to support multiple languages in your application, you would provide folders inside +your application/language/ directory for each of them, and you would specify the default +language in your application/config/config.php.

+

The application/language/english/ directory would contain any additional language files +needed by your application, for instance for error messages.

+

Each of the other idiom-specific directories would contain the core language files that you +obtained from the translations repositories, or that you translated yourself, as well as +any additional ones needed by your application.

+

You would store the language you are currently using, for instance in a session variable.

+
+

Sample Language Files

+
system/
+        language/
+                english/
+                        ...
+                        email_lang.php
+                        form_validation_lang.php
+                        ...
+
+application/
+        language/
+                english/
+                        error_messages_lang.php
+                french/
+                        ...
+                        email_lang.php
+                        error_messages_lang.php
+                        form_validation_lang.php
+                        ...
+
+
+
+
+

Example of switching languages

+
$idiom = $this->session->get_userdata('language');
+$this->lang->load('error_messages', $idiom);
+$oops = $this->lang->line('message_key');
+
+
+
+
+
+

Internationalization

+

The Language class in CodeIgniter is meant to provide an easy and lightweight +way to support multiplelanguages in your application. It is not meant to be a +full implementation of what is commonly called internationalization and localization.

+

We use the term “idiom” to refer to a language using its common name, +rather than using any of the international standards, such as “en”, “en-US”, +or “en-CA-x-ca” for English and some of its variants.

+
+

Note

+

There is nothing to prevent you from using those abbreviations in your application!

+
+
+
+

Using the Language Class

+
+

Creating Language Files

+

Language files must be named with _lang.php as the filename extension. +For example, let’s say you want to create a file containing error messages. +You might name it: error_lang.php

+

Within the file you will assign each line of text to an array called +$lang with this prototype:

+
$lang['language_key'] = 'The actual message to be shown';
+
+
+
+

Note

+

It’s a good practice to use a common prefix for all messages +in a given file to avoid collisions with similarly named items in other +files. For example, if you are creating error messages you might prefix +them with error_

+
+
$lang['error_email_missing'] = 'You must submit an email address';
+$lang['error_url_missing'] = 'You must submit a URL';
+$lang['error_username_missing'] = 'You must submit a username';
+
+
+
+
+

Loading A Language File

+

In order to fetch a line from a particular file you must load the file +first. Loading a language file is done with the following code:

+
$this->lang->load('filename', 'language');
+
+
+

Where filename is the name of the file you wish to load (without the +file extension), and language is the language set containing it (ie, +english). If the second parameter is missing, the default language set +in your application/config/config.php file will be used.

+

You can also load multiple language files at the same time by passing an array of language files as first parameter.

+
$this->lang->load(array('filename1', 'filename2'));
+
+
+
+

Note

+

The language parameter can only consist of letters.

+
+
+
+

Fetching a Line of Text

+

Once your desired language file is loaded you can access any line of +text using this function:

+
$this->lang->line('language_key');
+
+
+

Where language_key is the array key corresponding to the line you wish +to show.

+

You can optionally pass FALSE as the second argument of that method to +disable error logging, in case you’re not sure if the line exists:

+
$this->lang->line('misc_key', FALSE);
+
+
+
+

Note

+

This method simply returns the line. It does not echo it.

+
+
+

Using language lines as form labels

+

This feature has been deprecated from the language library and moved to +the lang() function of the Language Helper.

+
+
+
+

Auto-loading Languages

+

If you find that you need a particular language 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 +language(s) to the autoload array.

+
+
+
+

Class Reference

+
+
+class CI_Lang
+
+
+load($langfile[, $idiom = ''[, $return = FALSE[, $add_suffix = TRUE[, $alt_path = '']]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $langfile (mixed) – Language file to load or array with multiple files
  • +
  • $idiom (string) – Language name (i.e. ‘english’)
  • +
  • $return (bool) – Whether to return the loaded array of translations
  • +
  • $add_suffix (bool) – Whether to add the ‘_lang’ suffix to the language file name
  • +
  • $alt_path (string) – An alternative path to look in for the language file
  • +
+
Returns:

Array of language lines if $return is set to TRUE, otherwise void

+
Return type:

mixed

+
+

Loads a language file.

+
+ +
+
+line($line[, $log_errors = TRUE])
+
+++ + + + + + + + +
Parameters:
    +
  • $line (string) – Language line key name
  • +
  • $log_errors (bool) – Whether to log an error if the line isn’t found
  • +
+
Returns:

Language line string or FALSE on failure

+
Return type:

string

+
+

Fetches a single translation line from the already loaded language files, +based on the line’s name.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/loader.html b/user_guide/libraries/loader.html new file mode 100644 index 000000000..763481304 --- /dev/null +++ b/user_guide/libraries/loader.html @@ -0,0 +1,1213 @@ + + + + + + + + + + Loader Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Loader Class

+

Loader, as the name suggests, is used to load elements. These elements +can be libraries (classes) View files, +Drivers, +Helpers, +Models, or your own files.

+
+

Note

+

This class is initialized automatically by the system so there +is no need to do it manually.

+
+ +
+

Application “Packages”

+

An application package allows for the easy distribution of complete sets +of resources in a single directory, complete with its own libraries, +models, helpers, config, and language files. It is recommended that +these packages be placed in the application/third_party directory. Below +is a sample map of an package directory.

+

The following is an example of a directory for an application package +named “Foo Bar”.

+
/application/third_party/foo_bar
+
+config/
+helpers/
+language/
+libraries/
+models/
+
+
+

Whatever the purpose of the “Foo Bar” application package, it has its +own config files, helpers, language files, libraries, and models. To use +these resources in your controllers, you first need to tell the Loader +that you are going to be loading resources from a package, by adding the +package path via the add_package_path() method.

+
+

Package view files

+

By Default, package view files paths are set when add_package_path() +is called. View paths are looped through, and once a match is +encountered that view is loaded.

+

In this instance, it is possible for view naming collisions within +packages to occur, and possibly the incorrect package being loaded. To +ensure against this, set an optional second parameter of FALSE when +calling add_package_path().

+
$this->load->add_package_path(APPPATH.'my_app', FALSE);
+$this->load->view('my_app_index'); // Loads
+$this->load->view('welcome_message'); // Will not load the default welcome_message b/c the second param to add_package_path is FALSE
+
+// Reset things
+$this->load->remove_package_path(APPPATH.'my_app');
+
+// Again without the second parameter:
+$this->load->add_package_path(APPPATH.'my_app');
+$this->load->view('my_app_index'); // Loads
+$this->load->view('welcome_message'); // Loads
+
+
+
+
+
+

Class Reference

+
+
+class CI_Loader
+
+
+library($library[, $params = NULL[, $object_name = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $library (mixed) – Library name as a string or an array with multiple libraries
  • +
  • $params (array) – Optional array of parameters to pass to the loaded library’s constructor
  • +
  • $object_name (string) – Optional object name to assign the library to
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

This method is used to load core classes.

+
+

Note

+

We use the terms “class” and “library” interchangeably.

+
+

For example, if you would like to send email with CodeIgniter, the first +step is to load the email class within your controller:

+
$this->load->library('email');
+
+
+

Once loaded, the library will be ready for use, using $this->email.

+

Library files can be stored in subdirectories within the main +“libraries” directory, or within your personal application/libraries +directory. To load a file located in a subdirectory, simply include the +path, relative to the “libraries” directory. For example, if you have +file located at:

+
libraries/flavors/Chocolate.php
+
+
+

You will load it using:

+
$this->load->library('flavors/chocolate');
+
+
+

You may nest the file in as many subdirectories as you want.

+

Additionally, multiple libraries can be loaded at the same time by +passing an array of libraries to the load method.

+
$this->load->library(array('email', 'table'));
+
+
+

Setting options

+

The second (optional) parameter allows you to optionally pass +configuration setting. You will typically pass these as an array:

+
$config = array (
+        'mailtype' => 'html',
+        'charset'  => 'utf-8',
+        'priority' => '1'
+);
+
+$this->load->library('email', $config);
+
+
+

Config options can usually also be set via a config file. Each library +is explained in detail in its own page, so please read the information +regarding each one you would like to use.

+

Please take note, when multiple libraries are supplied in an array for +the first parameter, each will receive the same parameter information.

+

Assigning a Library to a different object name

+

If the third (optional) parameter is blank, the library will usually be +assigned to an object with the same name as the library. For example, if +the library is named Calendar, it will be assigned to a variable named +$this->calendar.

+

If you prefer to set your own class names you can pass its value to the +third parameter:

+
$this->load->library('calendar', NULL, 'my_calendar');
+
+// Calendar class is now accessed using:
+$this->my_calendar
+
+
+

Please take note, when multiple libraries are supplied in an array for +the first parameter, this parameter is discarded.

+
+ +
+
+driver($library[, $params = NULL[, $object_name]])
+
+++ + + + + + + + +
Parameters:
    +
  • $library (mixed) – Library name as a string or an array with multiple libraries
  • +
  • $params (array) – Optional array of parameters to pass to the loaded library’s constructor
  • +
  • $object_name (string) – Optional object name to assign the library to
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

This method is used to load driver libraries, acts very much like the +library() method.

+

As an example, if you would like to use sessions with CodeIgniter, the first +step is to load the session driver within your controller:

+
$this->load->driver('session');
+
+
+

Once loaded, the library will be ready for use, using $this->session.

+

Driver files must be stored in a subdirectory within the main +“libraries” directory, or within your personal application/libraries +directory. The subdirectory must match the parent class name. Read the +Drivers description for details.

+

Additionally, multiple driver libraries can be loaded at the same time by +passing an array of drivers to the load method.

+
$this->load->driver(array('session', 'cache'));
+
+
+

Setting options

+

The second (optional) parameter allows you to optionally pass +configuration settings. You will typically pass these as an array:

+
$config = array(
+        'sess_driver' => 'cookie',
+        'sess_encrypt_cookie'  => true,
+        'encryption_key' => 'mysecretkey'
+);
+
+$this->load->driver('session', $config);
+
+
+

Config options can usually also be set via a config file. Each library +is explained in detail in its own page, so please read the information +regarding each one you would like to use.

+

Assigning a Driver to a different object name

+

If the third (optional) parameter is blank, the library will be assigned +to an object with the same name as the parent class. For example, if +the library is named Session, it will be assigned to a variable named +$this->session.

+

If you prefer to set your own class names you can pass its value to the +third parameter:

+
$this->load->library('session', '', 'my_session');
+
+// Session class is now accessed using:
+$this->my_session
+
+
+
+ +
+
+view($view[, $vars = array()[, return = FALSE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $view (string) – View name
  • +
  • $vars (array) – An associative array of variables
  • +
  • $return (bool) – Whether to return the loaded view
  • +
+
Returns:

View content string if $return is set to TRUE, otherwise CI_Loader instance (method chaining)

+
Return type:

mixed

+
+

This method is used to load your View files. If you haven’t read the +Views section of the user guide it is +recommended that you do since it shows you how this method is +typically used.

+

The first parameter is required. It is the name of the view file you +would like to load.

+
+

Note

+

The .php file extension does not need to be specified unless +you use something other than .php.

+
+

The second optional parameter can take an associative array or an +object as input, which it runs through the PHP +extract() function to convert to variables +that can be used in your view files. Again, read the +Views page to learn how this might be useful.

+

The 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);
+
+
+
+ +
+
+vars($vars[, $val = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $vars (mixed) – An array of variables or a single variable name
  • +
  • $val (mixed) – Optional variable value
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

This method takes an associative array as input and generates +variables using the PHP extract() +function. This method produces the same result as using the second +parameter of the $this->load->view() method above. The reason you +might want to use this method independently is if you would like to +set some global variables in the constructor of your controller and have +them become available in any view file loaded from any method. You can +have multiple calls to this method. The data get cached and merged +into one array for conversion to variables.

+
+ +
+
+get_var($key)
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Variable name key
  • +
+
Returns:

Value if key is found, NULL if not

+
Return type:

mixed

+
+

This method checks the associative array of variables available to +your views. This is useful if for any reason a var is set in a library +or another controller method using $this->load->vars().

+
+ +
+
+get_vars()
+
+++ + + + + + +
Returns:An array of all assigned view variables
Return type:array
+

This method retrieves all variables available to your views.

+
+ +
+
+clear_vars()
+
+++ + + + + + +
Returns:CI_Loader instance (method chaining)
Return type:CI_Loader
+

Clears cached view variables.

+
+ +
+
+model($model[, $name = ''[, $db_conn = FALSE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $model (mixed) – Model name or an array containing multiple models
  • +
  • $name (string) – Optional object name to assign the model to
  • +
  • $db_conn (string) – Optional database configuration group to load
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+
$this->load->model('model_name');
+
+
+

If your model is located in a subdirectory, 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');
+
+
+

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', 'fubar');
+$this->fubar->method();
+
+
+
+ +
+
+database([$params = ''[, $return = FALSE[, $query_builder = NULL]]])
+
+++ + + + + + + + +
Parameters:
    +
  • $params (mixed) – Database group name or configuration options
  • +
  • $return (bool) – Whether to return the loaded database object
  • +
  • $query_builder (bool) – Whether to load the Query Builder
  • +
+
Returns:

Loaded CI_DB instance or FALSE on failure if $return is set to TRUE, otherwise CI_Loader instance (method chaining)

+
Return type:

mixed

+
+

This method lets you load the database class. The two parameters are +optional. Please see the database +section for more info.

+
+ +
+
+dbforge([$db = NULL[, $return = FALSE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $db (object) – Database object
  • +
  • $return (bool) – Whether to return the Database Forge instance
  • +
+
Returns:

Loaded CI_DB_forge instance if $return is set to TRUE, otherwise CI_Loader instance (method chaining)

+
Return type:

mixed

+
+

Loads the Database Forge class, please refer +to that manual for more info.

+
+ +
+
+dbutil([$db = NULL[, $return = FALSE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $db (object) – Database object
  • +
  • $return (bool) – Whether to return the Database Utilities instance
  • +
+
Returns:

Loaded CI_DB_utility instance if $return is set to TRUE, otherwise CI_Loader instance (method chaining)

+
Return type:

mixed

+
+

Loads the Database Utilities class, please +refer to that manual for more info.

+
+ +
+
+helper($helpers)
+
+++ + + + + + + + +
Parameters:
    +
  • $helpers (mixed) – Helper name as a string or an array containing multiple helpers
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

This method loads helper files, where file_name is the name of the +file, without the _helper.php extension.

+
+ +
+
+file($path[, $return = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – File path
  • +
  • $return (bool) – Whether to return the loaded file
  • +
+
Returns:

File contents if $return is set to TRUE, otherwise CI_Loader instance (method chaining)

+
Return type:

mixed

+
+

This is a generic file loading method. Supply the filepath and name in +the first parameter and it will open and read the file. By default the +data is sent to your browser, just like a View file, but if you set the +second parameter to boolean TRUE it will instead return the data as a +string.

+
+ +
+
+language($files[, $lang = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $files (mixed) – Language file name or an array of multiple language files
  • +
  • $lang (string) – Language name
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

This method is an alias of the language loading +method: $this->lang->load().

+
+ +
+
+config($file[, $use_sections = FALSE[, $fail_gracefully = FALSE]])
+
+++ + + + + + + + +
Parameters:
    +
  • $file (string) – Configuration file name
  • +
  • $use_sections (bool) – Whether configuration values should be loaded into their own section
  • +
  • $fail_gracefully (bool) – Whether to just return FALSE in case of failure
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

This method is an alias of the config file loading +method: $this->config->load()

+
+ +
+
+is_loaded($class)
+
+++ + + + + + + + +
Parameters:
    +
  • $class (string) – Class name
  • +
+
Returns:

Singleton property name if found, FALSE if not

+
Return type:

mixed

+
+

Allows you to check if a class has already been loaded or not.

+
+

Note

+

The word “class” here refers to libraries and drivers.

+
+

If the requested class has been loaded, the method returns its assigned +name in the CI Super-object and FALSE if it’s not:

+
$this->load->library('form_validation');
+$this->load->is_loaded('Form_validation');      // returns 'form_validation'
+
+$this->load->is_loaded('Nonexistent_library');  // returns FALSE
+
+
+
+

Important

+

If you have more than one instance of a class (assigned to +different properties), then the first one will be returned.

+
+
$this->load->library('form_validation', $config, 'fv');
+$this->load->library('form_validation');
+
+$this->load->is_loaded('Form_validation');      // returns 'fv'
+
+
+
+ +
+
+add_package_path($path[, $view_cascade = TRUE])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Path to add
  • +
  • $view_cascade (bool) – Whether to use cascading views
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

Adding a package path instructs the Loader class to prepend a given path +for subsequent requests for resources. As an example, the “Foo Bar” +application package above has a library named Foo_bar.php. In our +controller, we’d do the following:

+
$this->load->add_package_path(APPPATH.'third_party/foo_bar/')
+        ->library('foo_bar');
+
+
+
+ +
+
+remove_package_path([$path = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Path to remove
  • +
+
Returns:

CI_Loader instance (method chaining)

+
Return type:

CI_Loader

+
+

When your controller is finished using resources from an application +package, and particularly if you have other application packages you +want to work with, you may wish to remove the package path so the Loader +no longer looks in that directory for resources. To remove the last path +added, simply call the method with no parameters.

+

Or to remove a specific package path, specify the same path previously +given to add_package_path() for a package.:

+
$this->load->remove_package_path(APPPATH.'third_party/foo_bar/');
+
+
+
+ +
+
+get_package_paths([$include_base = TRUE])
+
+++ + + + + + + + +
Parameters:
    +
  • $include_base (bool) – Whether to include BASEPATH
  • +
+
Returns:

An array of package paths

+
Return type:

array

+
+

Returns all currently available package paths.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/migration.html b/user_guide/libraries/migration.html new file mode 100644 index 000000000..fb0afe7fe --- /dev/null +++ b/user_guide/libraries/migration.html @@ -0,0 +1,758 @@ + + + + + + + + + + Migrations Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Migrations Class

+

Migrations are a convenient way for you to alter your database in a +structured and organized manner. You could edit fragments of SQL by hand +but you would then be responsible for telling other developers that they +need to go and run them. You would also have to keep track of which changes +need to be run against the production machines next time you deploy.

+

The database table migration tracks which migrations have already been +run so all you have to do is update your application files and +call $this->migration->current() to work out which migrations should be run. +The current version is found in application/config/migration.php.

+ +
+

Migration file names

+

Each Migration is run in numeric order forward or backwards depending on the +method taken. Two numbering styles are available:

+
    +
  • Sequential: each migration is numbered in sequence, starting with 001. +Each number must be three digits, and there must not be any gaps in the +sequence. (This was the numbering scheme prior to CodeIgniter 3.0.)
  • +
  • Timestamp: each migration is numbered using the timestamp when the migration +was created, in YYYYMMDDHHIISS format (e.g. 20121031100537). This +helps prevent numbering conflicts when working in a team environment, and is +the preferred scheme in CodeIgniter 3.0 and later.
  • +
+

The desired style may be selected using the $config['migration_type'] +setting in your application/config/migration.php file.

+

Regardless of which numbering style you choose to use, prefix your migration +files with the migration number followed by an underscore and a descriptive +name for the migration. For example:

+
    +
  • 001_add_blog.php (sequential numbering)
  • +
  • 20121031100537_add_blog.php (timestamp numbering)
  • +
+
+
+

Create a Migration

+

This will be the first migration for a new site which has a blog. All +migrations go in the application/migrations/ directory and have names such +as 20121031100537_add_blog.php.

+
<?php
+
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+class Migration_Add_blog extends CI_Migration {
+
+        public function up()
+        {
+                $this->dbforge->add_field(array(
+                        'blog_id' => array(
+                                'type' => 'INT',
+                                'constraint' => 5,
+                                'unsigned' => TRUE,
+                                'auto_increment' => TRUE
+                        ),
+                        'blog_title' => array(
+                                'type' => 'VARCHAR',
+                                'constraint' => '100',
+                        ),
+                        'blog_description' => array(
+                                'type' => 'TEXT',
+                                'null' => TRUE,
+                        ),
+                ));
+                $this->dbforge->add_key('blog_id', TRUE);
+                $this->dbforge->create_table('blog');
+        }
+
+        public function down()
+        {
+                $this->dbforge->drop_table('blog');
+        }
+}
+
+
+

Then in application/config/migration.php set $config['migration_version'] = 20121031100537;.

+
+
+

Usage Example

+

In this example some simple code is placed in application/controllers/Migrate.php +to update the schema.:

+
<?php
+
+class Migrate extends CI_Controller
+{
+
+        public function index()
+        {
+                $this->load->library('migration');
+
+                if ($this->migration->current() === FALSE)
+                {
+                        show_error($this->migration->error_string());
+                }
+        }
+
+}
+
+
+
+
+

Migration Preferences

+

The following is a table of all the config options for migrations.

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefaultOptionsDescription
migration_enabledFALSETRUE / FALSEEnable or disable migrations.
migration_pathAPPPATH.’migrations/’NoneThe path to your migrations folder.
migration_version0NoneThe current version your database should use.
migration_tablemigrationsNoneThe table name for storing the schema +version number.
migration_auto_latestFALSETRUE / FALSEEnable or disable automatically +running migrations.
migration_type‘timestamp’‘timestamp’ / ‘sequential’The type of numeric identifier used to name +migration files.
+
+
+

Class Reference

+
+
+class CI_Migration
+
+
+current()
+
+++ + + + + + +
Returns:TRUE if no migrations are found, current version string on success, FALSE on failure
Return type:mixed
+

Migrates up to the current version (whatever is set for +$config['migration_version'] in application/config/migration.php).

+
+ +
+
+error_string()
+
+++ + + + + + +
Returns:Error messages
Return type:string
+

This returns a string of errors that were detected while performing a migration.

+
+ +
+
+find_migrations()
+
+++ + + + + + +
Returns:An array of migration files
Return type:array
+

An array of migration filenames are returned that are found in the migration_path property.

+
+ +
+
+latest()
+
+++ + + + + + +
Returns:Current version string on success, FALSE on failure
Return type:mixed
+

This works much the same way as current() but instead of looking for +the $config['migration_version'] the Migration class will use the very +newest migration found in the filesystem.

+
+ +
+
+version($target_version)
+
+++ + + + + + + + +
Parameters:
    +
  • $target_version (mixed) – Migration version to process
  • +
+
Returns:

TRUE if no migrations are found, current version string on success, FALSE on failure

+
Return type:

mixed

+
+

Version can be used to roll back changes or step forwards programmatically to +specific versions. It works just like current() but ignores $config['migration_version'].

+
$this->migration->version(5);
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/output.html b/user_guide/libraries/output.html new file mode 100644 index 000000000..a4c208832 --- /dev/null +++ b/user_guide/libraries/output.html @@ -0,0 +1,912 @@ + + + + + + + + + + Output Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Output Class

+

The Output class is a core class with one main function: To send the +finalized web page to the requesting browser. It is also responsible for +caching your web pages, if you use that +feature.

+
+

Note

+

This class is initialized automatically by the system so there +is no need to do it manually.

+
+

Under normal circumstances you won’t even notice the Output class since +it works transparently without your intervention. For example, when you +use the Loader class to load a view file, +it’s automatically passed to the Output class, which will be called +automatically by CodeIgniter at the end of system execution. It is +possible, however, for you to manually intervene with the output if you +need to.

+ +
+

Class Reference

+
+
+class CI_Output
+
+
+$parse_exec_vars = TRUE;
+

Enables/disables parsing of the {elapsed_time} and {memory_usage} pseudo-variables.

+

CodeIgniter will parse those tokens in your output by default. To disable this, set +this property to FALSE in your controller.

+
$this->output->parse_exec_vars = FALSE;
+
+
+
+ +
+
+set_output($output)
+
+++ + + + + + + + +
Parameters:
    +
  • $output (string) – String to set the output to
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Permits you to manually set the final output string. Usage example:

+
$this->output->set_output($data);
+
+
+
+

Important

+

If you do set your output manually, it must be the last thing done +in the function you call it from. For example, if you build a page in one +of your controller methods, don’t set the output until the end.

+
+
+ +
+
+set_content_type($mime_type[, $charset = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $mime_type (string) – MIME Type idenitifer string
  • +
  • $charset (string) – Character set
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Permits you to set the mime-type of your page so you can serve JSON data, JPEG’s, XML, etc easily.

+
$this->output
+        ->set_content_type('application/json')
+        ->set_output(json_encode(array('foo' => 'bar')));
+
+$this->output
+        ->set_content_type('jpeg') // You could also use ".jpeg" which will have the full stop removed before looking in config/mimes.php
+        ->set_output(file_get_contents('files/something.jpg'));
+
+
+
+

Important

+

Make sure any non-mime string you pass to this method +exists in application/config/mimes.php or it will have no effect.

+
+

You can also set the character set of the document, by passing a second argument:

+
$this->output->set_content_type('css', 'utf-8');
+
+
+
+ +
+
+get_content_type()
+
+++ + + + + + +
Returns:Content-Type string
Return type:string
+

Returns the Content-Type HTTP header that’s currently in use, excluding the character set value.

+
$mime = $this->output->get_content_type();
+
+
+
+

Note

+

If not set, the default return value is ‘text/html’.

+
+
+ +
+
+get_header($header)
+
+++ + + + + + + + +
Parameters:
    +
  • $header (string) – HTTP header name
  • +
+
Returns:

HTTP response header or NULL if not found

+
Return type:

mixed

+
+

Returns the requested HTTP header value, or NULL if the requested header is not set. +Example:

+
$this->output->set_content_type('text/plain', 'UTF-8');
+echo $this->output->get_header('content-type');
+// Outputs: text/plain; charset=utf-8
+
+
+
+

Note

+

The header name is compared in a case-insensitive manner.

+
+
+

Note

+

Raw headers sent via PHP’s native header() function are also detected.

+
+
+ +
+
+get_output()
+
+++ + + + + + +
Returns:Output string
Return type:string
+

Permits you to manually retrieve any output that has been sent for +storage in the output class. Usage example:

+
$string = $this->output->get_output();
+
+
+

Note that data will only be retrievable from this function if it has +been previously sent to the output class by one of the CodeIgniter +functions like $this->load->view().

+
+ +
+
+append_output($output)
+
+++ + + + + + + + +
Parameters:
    +
  • $output (string) – Additional output data to append
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Appends data onto the output string.

+
$this->output->append_output($data);
+
+
+
+ +
+
+set_header($header[, $replace = TRUE])
+
+++ + + + + + + + +
Parameters:
    +
  • $header (string) – HTTP response header
  • +
  • $replace (bool) – Whether to replace the old header value, if it is already set
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Permits you to manually set server headers, which the output class will +send for you when outputting the final rendered display. Example:

+
$this->output->set_header('HTTP/1.0 200 OK');
+$this->output->set_header('HTTP/1.1 200 OK');
+$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT');
+$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
+$this->output->set_header('Cache-Control: post-check=0, pre-check=0');
+$this->output->set_header('Pragma: no-cache');
+
+
+
+ +
+
+set_status_header([$code = 200[, $text = '']])
+
+++ + + + + + + + +
Parameters:
    +
  • $code (int) – HTTP status code
  • +
  • $text (string) – Optional message
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Permits you to manually set a server status header. Example:

+
$this->output->set_status_header(401);
+// Sets the header as:  Unauthorized
+
+
+

See here for a full list of headers.

+
+

Note

+

This method is an alias for Common function +set_status_header().

+
+
+ +
+
+enable_profiler([$val = TRUE])
+
+++ + + + + + + + +
Parameters:
    +
  • $val (bool) – Whether to enable or disable the Profiler
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Permits you to enable/disable the Profiler, which will display benchmark +and other data at the bottom of your pages for debugging and optimization purposes.

+

To enable the profiler place the following line anywhere within your +Controller 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 would use:

+
$this->output->enable_profiler(FALSE);
+
+
+
+ +
+
+set_profiler_sections($sections)
+
+++ + + + + + + + +
Parameters:
    +
  • $sections (array) – Profiler sections
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Permits you to enable/disable specific sections of the Profiler when it is enabled. +Please refer to the Profiler documentation for further information.

+
+ +
+
+cache($time)
+
+++ + + + + + + + +
Parameters:
    +
  • $time (int) – Cache expiration time in minutes
  • +
+
Returns:

CI_Output instance (method chaining)

+
Return type:

CI_Output

+
+

Caches the current page for the specified amount of minutes.

+

For more information, please see the caching documentation.

+
+ +
+
+_display([$output = ''])
+
+++ + + + + + + + +
Parameters:
    +
  • $output (string) – Output data override
  • +
+
Returns:

void

+
Return type:

void

+
+

Sends finalized output data to the browser along with any server headers. It also stops benchmark +timers.

+
+

Note

+

This method is called automatically at the end of script execution, you won’t need to +call it manually unless you are aborting script execution using exit() or die() in your code.

+
+

Example:

+
$response = array('status' => 'OK');
+
+$this->output
+        ->set_status_header(200)
+        ->set_content_type('application/json', 'utf-8')
+        ->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
+        ->_display();
+exit;
+
+
+
+

Note

+

Calling this method manually without aborting script execution will result in duplicated output.

+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/pagination.html b/user_guide/libraries/pagination.html new file mode 100644 index 000000000..1e3db5494 --- /dev/null +++ b/user_guide/libraries/pagination.html @@ -0,0 +1,784 @@ + + + + + + + + + + Pagination Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Pagination Class

+

CodeIgniter’s Pagination class is very easy to use, and it is 100% +customizable, either dynamically or via stored preferences.

+ +

If you are not familiar with the term “pagination”, it refers to links +that allows you to navigate from page to page, like this:

+
« First  < 1 2 3 4 5 >  Last »
+
+
+
+

Example

+

Here is a simple example showing how to create pagination in one of your +controller methods:

+
$this->load->library('pagination');
+
+$config['base_url'] = 'http://example.com/index.php/test/page/';
+$config['total_rows'] = 200;
+$config['per_page'] = 20;
+
+$this->pagination->initialize($config);
+
+echo $this->pagination->create_links();
+
+
+
+

Notes

+

The $config array contains your configuration variables. It is passed to +the $this->pagination->initialize() method as shown above. Although +there are some twenty items you can configure, at minimum you need the +three shown. Here is a description of what those items represent:

+
    +
  • base_url This is the full URL to the controller class/function +containing your pagination. In the example above, it is pointing to a +controller called “Test” and a function called “page”. Keep in mind +that you can re-route your URI if you +need a different structure.
  • +
  • total_rows This number represents the total rows in the result +set you are creating pagination for. Typically this number will be +the total rows that your database query returned.
  • +
  • per_page The number of items you intend to show per page. In the +above example, you would be showing 20 items per page.
  • +
+

The create_links() method returns an empty string when there is no +pagination to show.

+
+
+

Setting preferences in a config file

+

If you prefer not to set preferences using the above method, you can +instead put them into a config file. Simply create a new file called +pagination.php, add the $config array in that file. Then save the file +in application/config/pagination.php and it will be used automatically. +You will NOT need to use $this->pagination->initialize() if you save +your preferences in a config file.

+
+
+
+

Customizing the Pagination

+

The following is a list of all the preferences you can pass to the +initialization function to tailor the display.

+

$config[‘uri_segment’] = 3;

+

The pagination function automatically determines which segment of your +URI contains the page number. If you need something different you can +specify it.

+

$config[‘num_links’] = 2;

+

The number of “digit” links you would like before and after the selected +page number. For example, the number 2 will place two digits on either +side, as in the example links at the very top of this page.

+

$config[‘use_page_numbers’] = TRUE;

+

By default, the URI segment will use the starting index for the items +you are paginating. If you prefer to show the the actual page number, +set this to TRUE.

+

$config[‘page_query_string’] = TRUE;

+

By default, the pagination library assume you are using URI +Segments, and constructs your links something +like:

+
http://example.com/index.php/test/page/20
+
+
+

If you have $config['enable_query_strings'] set to TRUE your links +will automatically be re-written using Query Strings. This option can +also be explicitly set. Using $config['page_query_string'] set to TRUE, +the pagination link will become:

+
http://example.com/index.php?c=test&m=page&per_page=20
+
+
+

Note that “per_page” is the default query string passed, however can be +configured using $config['query_string_segment'] = 'your_string'

+

$config[‘reuse_query_string’] = FALSE;

+

By default your Query String arguments (nothing to do with other +query string options) will be ignored. Setting this config to +TRUE will add existing query string arguments back into the +URL after the URI segment and before the suffix.:

+
http://example.com/index.php/test/page/20?query=search%term
+
+
+

This helps you mix together normal URI Segments +as well as query string arguments, which until 3.0 was not possible.

+

$config[‘prefix’] = ‘’;

+

A custom prefix added to the path. The prefix value will be right before +the offset segment.

+

$config[‘suffix’] = ‘’;

+

A custom suffix added to the path. The suffix value will be right after +the offset segment.

+

$config[‘use_global_url_suffix’] = FALSE;

+

When set to TRUE, it will override the $config['suffix'] value and +instead set it to the one that you have in $config['url_suffix'] in +your application/config/config.php file.

+
+
+

Adding Enclosing Markup

+

If you would like to surround the entire pagination with some markup you +can do it with these two preferences:

+

$config[‘full_tag_open’] = ‘<p>’;

+

The opening tag placed on the left side of the entire result.

+

$config[‘full_tag_close’] = ‘</p>’;

+

The closing tag placed on the right side of the entire result.

+
+ + + + + + +
+

Hiding the Pages

+

If you wanted to not list the specific pages (for example, you only want +“next” and “previous” links), you can suppress their rendering by +adding:

+
$config['display_pages'] = FALSE;
+
+
+
+
+

Adding attributes to anchors

+

If you want to add an extra attribute to be added to every link rendered +by the pagination class, you can set them as key/value pairs in the +“attributes” config:

+
// Produces: class="myclass"
+$config['attributes'] = array('class' => 'myclass');
+
+
+
+

Note

+

Usage of the old method of setting classes via “anchor_class” +is deprecated.

+
+
+
+

Disabling the “rel” attribute

+

By default the rel attribute is dynamically generated and appended to +the appropriate anchors. If for some reason you want to turn it off, +you can pass boolean FALSE as a regular attribute

+
$config['attributes']['rel'] = FALSE;
+
+
+
+
+

Class Reference

+
+
+class CI_Pagination
+
+
+initialize([$params = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $params (array) – Configuration parameters
  • +
+
Returns:

CI_Pagination instance (method chaining)

+
Return type:

CI_Pagination

+
+

Initializes the Pagination class with your preferred options.

+
+ +
+ +
+++ + + + + + +
Returns:HTML-formatted pagination
Return type:string
+

Returns a “pagination” bar, containing the generated links or an empty string if there’s just a single page.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/parser.html b/user_guide/libraries/parser.html new file mode 100644 index 000000000..99ae9325a --- /dev/null +++ b/user_guide/libraries/parser.html @@ -0,0 +1,850 @@ + + + + + + + + + + Template Parser Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Template Parser Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Template Parser Class

+

The Template Parser Class can perform simple text substitution for +pseudo-variables contained within your view files. +It can parse simple variables or variable tag pairs.

+

If you’ve never used a template engine, +pseudo-variable names are enclosed in braces, like this:

+
<html>
+        <head>
+                <title>{blog_title}</title>
+        </head>
+        <body>
+                <h3>{blog_heading}</h3>
+
+        {blog_entries}
+                <h5>{title}</h5>
+                <p>{body}</p>
+        {/blog_entries}
+
+        </body>
+</html>
+
+
+

These variables are not actual PHP variables, but rather plain text +representations that allow you to eliminate PHP from your templates +(view files).

+
+

Note

+

CodeIgniter does not require you to use this class since +using pure PHP in your view pages lets them run a little faster. +However, some developers prefer to use a template engine if +they work with designers who they feel would find some +confusion working with PHP.

+
+
+

Important

+

The Template Parser Class is not a full-blown +template parsing solution. We’ve kept it very lean on purpose in order +to maintain maximum performance.

+
+ +
+

Using the Template Parser Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Parser class is initialized +in your controller using the $this->load->library() method:

+
$this->load->library('parser');
+
+
+

Once loaded, the Parser library object will be available using: +$this->parser

+
+
+

Parsing templates

+

You can use the parse() method to parse (or render) simple templates, +like this:

+
$data = array(
+        'blog_title' => 'My Blog Title',
+        'blog_heading' => 'My Blog Heading'
+);
+
+$this->parser->parse('blog_template', $data);
+
+
+

The first parameter contains the name of the view +file (in this example the file would be called +blog_template.php), and the second parameter contains an associative +array of data to be replaced in the template. In the above example, the +template would contain two variables: {blog_title} and {blog_heading}

+

There is no need to “echo” or do something with the data returned by +$this->parser->parse(). It is automatically passed to the output class +to be sent to the browser. However, if you do want the data returned +instead of sent to the output class you can pass TRUE (boolean) as the +third parameter:

+
$string = $this->parser->parse('blog_template', $data, TRUE);
+
+
+
+
+

Variable Pairs

+

The above example code allows simple variables to be replaced. What if +you would like an entire block of variables to be repeated, with each +iteration containing new values? Consider the template example we showed +at the top of the page:

+
<html>
+        <head>
+                <title>{blog_title}</title>
+        </head>
+        <body>
+                <h3>{blog_heading}</h3>
+
+        {blog_entries}
+                <h5>{title}</h5>
+                <p>{body}</p>
+        {/blog_entries}
+
+        </body>
+</html>
+
+
+

In the above code you’ll notice a pair of variables: {blog_entries} +data… {/blog_entries}. In a case like this, the entire chunk of data +between these pairs would be repeated multiple times, corresponding to +the number of rows in the “blog_entries” element of the parameters array.

+

Parsing variable pairs is done using the identical code shown above to +parse single variables, except, you will add a multi-dimensional array +corresponding to your variable pair data. Consider this example:

+
$this->load->library('parser');
+
+$data = array(
+        'blog_title'   => 'My Blog Title',
+        'blog_heading' => 'My Blog Heading',
+        'blog_entries' => array(
+                array('title' => 'Title 1', 'body' => 'Body 1'),
+                array('title' => 'Title 2', 'body' => 'Body 2'),
+                array('title' => 'Title 3', 'body' => 'Body 3'),
+                array('title' => 'Title 4', 'body' => 'Body 4'),
+                array('title' => 'Title 5', 'body' => 'Body 5')
+        )
+);
+
+$this->parser->parse('blog_template', $data);
+
+
+

If your “pair” data is coming from a database result, which is already a +multi-dimensional array, you can simply use the database result_array() +method:

+
$query = $this->db->query("SELECT * FROM blog");
+
+$this->load->library('parser');
+
+$data = array(
+        'blog_title'   => 'My Blog Title',
+        'blog_heading' => 'My Blog Heading',
+        'blog_entries' => $query->result_array()
+);
+
+$this->parser->parse('blog_template', $data);
+
+
+
+
+

Usage Notes

+

If you include substitution parameters that are not referenced in your +template, they are ignored:

+
$template = 'Hello, {firstname} {lastname}';
+$data = array(
+        'title' => 'Mr',
+        'firstname' => 'John',
+        'lastname' => 'Doe'
+);
+$this->parser->parse_string($template, $data);
+
+// Result: Hello, John Doe
+
+
+

If you do not include a substitution parameter that is referenced in your +template, the original pseudo-variable is shown in the result:

+
$template = 'Hello, {firstname} {initials} {lastname}';
+$data = array(
+        'title' => 'Mr',
+        'firstname' => 'John',
+        'lastname' => 'Doe'
+);
+$this->parser->parse_string($template, $data);
+
+// Result: Hello, John {initials} Doe
+
+
+

If you provide a string substitution parameter when an array is expected, +i.e. for a variable pair, the substitution is done for the opening variable +pair tag, but the closing variable pair tag is not rendered properly:

+
$template = 'Hello, {firstname} {lastname} ({degrees}{degree} {/degrees})';
+$data = array(
+        'degrees' => 'Mr',
+        'firstname' => 'John',
+        'lastname' => 'Doe',
+        'titles' => array(
+                array('degree' => 'BSc'),
+                array('degree' => 'PhD')
+        )
+);
+$this->parser->parse_string($template, $data);
+
+// Result: Hello, John Doe (Mr{degree} {/degrees})
+
+
+

If you name one of your individual substitution parameters the same as one +used inside a variable pair, the results may not be as expected:

+
$template = 'Hello, {firstname} {lastname} ({degrees}{degree} {/degrees})';
+$data = array(
+        'degree' => 'Mr',
+        'firstname' => 'John',
+        'lastname' => 'Doe',
+        'degrees' => array(
+                array('degree' => 'BSc'),
+                array('degree' => 'PhD')
+        )
+);
+$this->parser->parse_string($template, $data);
+
+// Result: Hello, John Doe (Mr Mr )
+
+
+
+
+

View Fragments

+

You do not have to use variable pairs to get the effect of iteration in +your views. It is possible to use a view fragment for what would be inside +a variable pair, and to control the iteration in your controller instead +of in the view.

+

An example with the iteration controlled in the view:

+
$template = '<ul>{menuitems}
+        <li><a href="{link}">{title}</a></li>
+{/menuitems}</ul>';
+
+$data = array(
+        'menuitems' => array(
+                array('title' => 'First Link', 'link' => '/first'),
+                array('title' => 'Second Link', 'link' => '/second'),
+        )
+);
+$this->parser->parse_string($template, $data);
+
+
+

Result:

+
<ul>
+        <li><a href="/first">First Link</a></li>
+        <li><a href="/second">Second Link</a></li>
+</ul>
+
+
+

An example with the iteration controlled in the controller, +using a view fragment:

+
$temp = '';
+$template1 = '<li><a href="{link}">{title}</a></li>';
+$data1 = array(
+        array('title' => 'First Link', 'link' => '/first'),
+        array('title' => 'Second Link', 'link' => '/second'),
+);
+
+foreach ($data1 as $menuitem)
+{
+        $temp .= $this->parser->parse_string($template1, $menuitem, TRUE);
+}
+
+$template = '<ul>{menuitems}</ul>';
+$data = array(
+        'menuitems' => $temp
+);
+$this->parser->parse_string($template, $data);
+
+
+

Result:

+
<ul>
+        <li><a href="/first">First Link</a></li>
+        <li><a href="/second">Second Link</a></li>
+</ul>
+
+
+
+
+
+

Class Reference

+
+
+class CI_Parser
+
+
+parse($template, $data[, $return = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $template (string) – Path to view file
  • +
  • $data (array) – Variable data
  • +
  • $return (bool) – Whether to only return the parsed template
  • +
+
Returns:

Parsed template string

+
Return type:

string

+
+

Parses a template from the provided path and variables.

+
+ +
+
+parse_string($template, $data[, $return = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $template (string) – Path to view file
  • +
  • $data (array) – Variable data
  • +
  • $return (bool) – Whether to only return the parsed template
  • +
+
Returns:

Parsed template string

+
Return type:

string

+
+

This method works exactly like parse(), only it accepts +the template as a string instead of loading a view file.

+
+ +
+
+set_delimiters([$l = '{'[, $r = '}']])
+
+++ + + + + + +
Parameters:
    +
  • $l (string) – Left delimiter
  • +
  • $r (string) – Right delimiter
  • +
+
Return type:

void

+
+

Sets the delimiters (opening and closing) for a +pseudo-variable “tag” in a template.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/security.html b/user_guide/libraries/security.html new file mode 100644 index 000000000..20469675d --- /dev/null +++ b/user_guide/libraries/security.html @@ -0,0 +1,739 @@ + + + + + + + + + + Security Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Security Class

+

The Security Class contains methods that help you create a secure +application, processing input data for security.

+ +
+

XSS Filtering

+

CodeIgniter comes with a Cross Site Scripting prevention filter, which +looks for commonly used techniques to trigger JavaScript or other types +of code that attempt to hijack cookies or do other malicious things. +If anything disallowed is encountered it is rendered safe by converting +the data to character entities.

+

To filter data through the XSS filter use the xss_clean() method:

+
$data = $this->security->xss_clean($data);
+
+
+

An optional second parameter, is_image, allows this function to be used +to test images for potential XSS attacks, useful for file upload +security. When this second parameter is set to TRUE, instead of +returning an altered string, the function returns TRUE if the image is +safe, and FALSE if it contained potentially malicious information that a +browser may attempt to execute.

+
if ($this->security->xss_clean($file, TRUE) === FALSE)
+{
+        // file failed the XSS test
+}
+
+
+
+

Important

+

If you want to filter HTML attribute values, use +html_escape() instead!

+
+
+
+

Cross-site request forgery (CSRF)

+

You can enable CSRF protection by altering your application/config/config.php +file in the following way:

+
$config['csrf_protection'] = TRUE;
+
+
+

If you use the form helper, then +form_open() will automatically insert a hidden csrf field in +your forms. If not, then you can use get_csrf_token_name() +and get_csrf_hash()

+
$csrf = array(
+        'name' => $this->security->get_csrf_token_name(),
+        'hash' => $this->security->get_csrf_hash()
+);
+
+...
+
+<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />
+
+
+

Tokens may be either regenerated on every submission (default) or +kept the same throughout the life of the CSRF cookie. The default +regeneration of tokens provides stricter security, but may result +in usability concerns as other tokens become invalid (back/forward +navigation, multiple tabs/windows, asynchronous actions, etc). You +may alter this behavior by editing the following config parameter

+
$config['csrf_regenerate'] = TRUE;
+
+
+

Select URIs can be whitelisted from csrf protection (for example API +endpoints expecting externally POSTed content). You can add these URIs +by editing the ‘csrf_exclude_uris’ config parameter:

+
$config['csrf_exclude_uris'] = array('api/person/add');
+
+
+

Regular expressions are also supported (case-insensitive):

+
$config['csrf_exclude_uris'] = array(
+        'api/record/[0-9]+',
+        'api/title/[a-z]+'
+);
+
+
+
+
+

Class Reference

+
+
+class CI_Security
+
+
+xss_clean($str[, $is_image = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $str (mixed) – Input string or an array of strings
  • +
+
Returns:

XSS-clean data

+
Return type:

mixed

+
+

Tries to remove XSS exploits from the input data and returns the cleaned string. +If the optional second parameter is set to true, it will return boolean TRUE if +the image is safe to use and FALSE if malicious data was detected in it.

+
+

Important

+

This method is not suitable for filtering HTML attribute values! +Use html_escape() for that instead.

+
+
+ +
+
+sanitize_filename($str[, $relative_path = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – File name/path
  • +
  • $relative_path (bool) – Whether to preserve any directories in the file path
  • +
+
Returns:

Sanitized file name/path

+
Return type:

string

+
+

Tries to sanitize filenames in order to prevent directory traversal attempts +and other security threats, which is particularly useful for files that were supplied via user input.

+
$filename = $this->security->sanitize_filename($this->input->post('filename'));
+
+
+

If it is acceptable for the user input to include relative paths, e.g. +file/in/some/approved/folder.txt, you can set the second optional parameter, $relative_path to TRUE.

+
$filename = $this->security->sanitize_filename($this->input->post('filename'), TRUE);
+
+
+
+ +
+
+get_csrf_token_name()
+
+++ + + + + + +
Returns:CSRF token name
Return type:string
+

Returns the CSRF token name (the $config['csrf_token_name'] value).

+
+ +
+
+get_csrf_hash()
+
+++ + + + + + +
Returns:CSRF hash
Return type:string
+

Returns the CSRF hash value. Useful in combination with get_csrf_token_name() +for manually building forms or sending valid AJAX POST requests.

+
+ +
+
+entity_decode($str[, $charset = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
  • $charset (string) – Character set of the input string
  • +
+
Returns:

Entity-decoded string

+
Return type:

string

+
+

This method acts a lot like PHP’s own native html_entity_decode() function in ENT_COMPAT mode, only +it tries to detect HTML entities that don’t end in a semicolon because some browsers allow that.

+

If the $charset parameter is left empty, then your configured $config['charset'] value will be used.

+
+ +
+
+get_random_bytes($length)
+
+++ + + + + + + + +
Parameters:
    +
  • $length (int) – Output length
  • +
+
Returns:

A binary stream of random bytes or FALSE on failure

+
Return type:

string

+
+

A convenience method for getting proper random bytes via mcrypt_create_iv(), +/dev/urandom or openssl_random_pseudo_bytes() (in that order), if one +of them is available.

+

Used for generating CSRF and XSS tokens.

+
+

Note

+

The output is NOT guaranteed to be cryptographically secure, +just the best attempt at that.

+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/sessions.html b/user_guide/libraries/sessions.html new file mode 100644 index 000000000..d3f4263d8 --- /dev/null +++ b/user_guide/libraries/sessions.html @@ -0,0 +1,1922 @@ + + + + + + + + + + Session Library — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Session Library

+

The Session class permits you maintain a user’s “state” and track their +activity while they browse your site.

+

CodeIgniter comes with a few session storage drivers:

+
+
    +
  • files (default; file-system based)
  • +
  • database
  • +
  • redis
  • +
  • memcached
  • +
+
+

In addition, you may create your own, custom session drivers based on other +kinds of storage, while still taking advantage of the features of the +Session class.

+ +
+

Using the Session Class

+
+

Initializing a Session

+

Sessions will typically run globally with each page load, so the Session +class should either be initialized in your controller constructors, or it can be auto-loaded by the system. +For the most part the session class will run unattended in the background, +so simply initializing the class will cause it to read, create, and update +sessions when necessary.

+

To initialize the Session class manually in your controller constructor, +use the $this->load->library() method:

+
$this->load->library('session');
+
+
+

Once loaded, the Sessions library object will be available using:

+
$this->session
+
+
+
+

Important

+

Because the Loader Class is instantiated +by CodeIgniter’s base controller, make sure to call +parent::__construct() before trying to load a library from +inside a controller constructor.

+
+
+
+

How do Sessions work?

+

When a page is loaded, the session class will check to see if valid +session cookie is sent by the user’s browser. If a sessions cookie does +not exist (or if it doesn’t match one stored on the server or has +expired) a new session will be created and saved.

+

If a valid session does exist, its information will be updated. With each +update, the session ID may be regenerated if configured to do so.

+

It’s important for you to understand that once initialized, the Session +class runs automatically. There is nothing you need to do to cause the +above behavior to happen. You can, as you’ll see below, work with session +data, but the process of reading, writing, and updating a session is +automatic.

+
+

Note

+

Under CLI, the Session library will automatically halt itself, +as this is a concept based entirely on the HTTP protocol.

+
+
+

A note about concurrency

+

Unless you’re developing a website with heavy AJAX usage, you can skip this +section. If you are, however, and if you’re experiencing performance +issues, then this note is exactly what you’re looking for.

+

Sessions in previous versions of CodeIgniter didn’t implement locking, +which meant that two HTTP requests using the same session could run exactly +at the same time. To use a more appropriate technical term - requests were +non-blocking.

+

However, non-blocking requests in the context of sessions also means +unsafe, because modifications to session data (or session ID regeneration) +in one request can interfere with the execution of a second, concurrent +request. This detail was at the root of many issues and the main reason why +CodeIgniter 3.0 has a completely re-written Session library.

+

Why are we telling you this? Because it is likely that after trying to +find the reason for your performance issues, you may conclude that locking +is the issue and therefore look into how to remove the locks …

+

DO NOT DO THAT! Removing locks would be wrong and it will cause you +more problems!

+

Locking is not the issue, it is a solution. Your issue is that you still +have the session open, while you’ve already processed it and therefore no +longer need it. So, what you need is to close the session for the +current request after you no longer need it.

+

Long story short - call session_write_close() once you no longer need +anything to do with session variables.

+
+
+
+

What is Session Data?

+

Session data is simply an array associated with a particular session ID +(cookie).

+

If you’ve used sessions in PHP before, you should be familiar with PHP’s +$_SESSION superglobal +(if not, please read the content on that link).

+

CodeIgniter gives access to its session data through the same means, as it +uses the session handlers’ mechanism provided by PHP. Using session data is +as simple as manipulating (read, set and unset values) the $_SESSION +array.

+

In addition, CodeIgniter also provides 2 special types of session data +that are further explained below: flashdata and tempdata.

+
+

Note

+

In previous versions, regular session data in CodeIgniter was +referred to as ‘userdata’. Have this in mind if that term is used +elsewhere in the manual. Most of it is written to explain how +the custom ‘userdata’ methods work.

+
+
+
+

Retrieving Session Data

+

Any piece of information from the session array is available through the +$_SESSION superglobal:

+
$_SESSION['item']
+
+
+

Or through the magic getter:

+
$this->session->item
+
+
+

And for backwards compatibility, through the userdata() method:

+
$this->session->userdata('item');
+
+
+

Where item is the array key corresponding to the item you wish to fetch. +For example, to assign a previously stored ‘name’ item to the $name +variable, you will do this:

+
$name = $_SESSION['name'];
+
+// or:
+
+$name = $this->session->name
+
+// or:
+
+$name = $this->session->userdata('name');
+
+
+
+

Note

+

The userdata() method returns NULL if the item you are trying +to access does not exist.

+
+

If you want to retrieve all of the existing userdata, you can simply +omit the item key (magic getter only works for properties):

+
$_SESSION
+
+// or:
+
+$this->session->userdata();
+
+
+
+
+

Adding Session Data

+

Let’s say a particular user logs into your site. Once authenticated, you +could add their username and e-mail address to the session, making that +data globally available to you without having to run a database query when +you need it.

+

You can simply assign data to the $_SESSION array, as with any other +variable. Or as a property of $this->session.

+

Alternatively, the old method of assigning it as “userdata” is also +available. That however passing an array containing your new data to the +set_userdata() method:

+
$this->session->set_userdata($array);
+
+
+

Where $array is an associative array containing your new data. Here’s +an example:

+
$newdata = array(
+        'username'  => 'johndoe',
+        'email'     => 'johndoe@some-site.com',
+        'logged_in' => TRUE
+);
+
+$this->session->set_userdata($newdata);
+
+
+

If you want to add userdata one value at a time, set_userdata() also +supports this syntax:

+
$this->session->set_userdata('some_name', 'some_value');
+
+
+

If you want to verify that a session value exists, simply check with +isset():

+
// returns FALSE if the 'some_name' item doesn't exist or is NULL,
+// TRUE otherwise:
+isset($_SESSION['some_name'])
+
+
+

Or you can call has_userdata():

+
$this->session->has_userdata('some_name');
+
+
+
+
+

Removing Session Data

+

Just as with any other variable, unsetting a value in $_SESSION can be +done through unset():

+
unset($_SESSION['some_name']);
+
+// or multiple values:
+
+unset(
+        $_SESSION['some_name'],
+        $_SESSION['another_name']
+);
+
+
+

Also, just as set_userdata() can be used to add information to a +session, unset_userdata() can be used to remove it, by passing the +session key. For example, if you wanted to remove ‘some_name’ from your +session data array:

+
$this->session->unset_userdata('some_name');
+
+
+

This method also accepts an array of item keys to unset:

+
$array_items = array('username', 'email');
+
+$this->session->unset_userdata($array_items);
+
+
+
+

Note

+

In previous versions, the unset_userdata() method used +to accept an associative array of key => 'dummy value' +pairs. This is no longer supported.

+
+
+
+

Flashdata

+

CodeIgniter supports “flashdata”, or session data that will only be +available for the next request, and is then automatically cleared.

+

This can be very useful, especially for one-time informational, error or +status messages (for example: “Record 2 deleted”).

+

It should be noted that flashdata variables are regular session vars, +only marked in a specific way under the ‘__ci_vars’ key (please don’t touch +that one, you’ve been warned).

+

To mark an existing item as “flashdata”:

+
$this->session->mark_as_flash('item');
+
+
+

If you want to mark multiple items as flashdata, simply pass the keys as an +array:

+
$this->session->mark_as_flash(array('item', 'item2'));
+
+
+

To add flashdata:

+
$_SESSION['item'] = 'value';
+$this->session->mark_as_flash('item');
+
+
+

Or alternatively, using the set_flashdata() method:

+
$this->session->set_flashdata('item', 'value');
+
+
+

You can also pass an array to set_flashdata(), in the same manner as +set_userdata().

+

Reading flashdata variables is the same as reading regular session data +through $_SESSION:

+
$_SESSION['item']
+
+
+
+

Important

+

The userdata() method will NOT return flashdata items.

+
+

However, if you want to be sure that you’re reading “flashdata” (and not +any other kind), you can also use the flashdata() method:

+
$this->session->flashdata('item');
+
+
+

Or to get an array with all flashdata, simply omit the key parameter:

+
$this->session->flashdata();
+
+
+
+

Note

+

The flashdata() method returns NULL if the item cannot be +found.

+
+

If you find that you need to preserve a flashdata variable through an +additional request, you can do so using the keep_flashdata() method. +You can either pass a single item or an array of flashdata items to keep.

+
$this->session->keep_flashdata('item');
+$this->session->keep_flashdata(array('item1', 'item2', 'item3'));
+
+
+
+
+

Tempdata

+

CodeIgniter also supports “tempdata”, or session data with a specific +expiration time. After the value expires, or the session expires or is +deleted, the value is automatically removed.

+

Similarly to flashdata, tempdata variables are regular session vars that +are marked in a specific way under the ‘__ci_vars’ key (again, don’t touch +that one).

+

To mark an existing item as “tempdata”, simply pass its key and expiry time +(in seconds!) to the mark_as_temp() method:

+
// 'item' will be erased after 300 seconds
+$this->session->mark_as_temp('item', 300);
+
+
+

You can mark multiple items as tempdata in two ways, depending on whether +you want them all to have the same expiry time or not:

+
// Both 'item' and 'item2' will expire after 300 seconds
+$this->session->mark_as_temp(array('item', 'item2'), 300);
+
+// 'item' will be erased after 300 seconds, while 'item2'
+// will do so after only 240 seconds
+$this->session->mark_as_temp(array(
+        'item'  => 300,
+        'item2' => 240
+));
+
+
+

To add tempdata:

+
$_SESSION['item'] = 'value';
+$this->session->mark_as_temp('item', 300); // Expire in 5 minutes
+
+
+

Or alternatively, using the set_tempdata() method:

+
$this->session->set_tempdata('item', 'value', 300);
+
+
+

You can also pass an array to set_tempdata():

+
$tempdata = array('newuser' => TRUE, 'message' => 'Thanks for joining!');
+
+$this->session->set_tempdata($tempdata, NULL, $expire);
+
+
+
+

Note

+

If the expiration is omitted or set to 0, the default +time-to-live value of 300 seconds (or 5 minutes) will be used.

+
+

To read a tempdata variable, again you can just access it through the +$_SESSION superglobal array:

+
$_SESSION['item']
+
+
+
+

Important

+

The userdata() method will NOT return tempdata items.

+
+

Or if you want to be sure that you’re reading “tempdata” (and not any +other kind), you can also use the tempdata() method:

+
$this->session->tempdata('item');
+
+
+

And of course, if you want to retrieve all existing tempdata:

+
$this->session->tempdata();
+
+
+
+

Note

+

The tempdata() method returns NULL if the item cannot be +found.

+
+

If you need to remove a tempdata value before it expires, you can directly +unset it from the $_SESSION array:

+
unset($_SESSION['item']);
+
+
+

However, this won’t remove the marker that makes this specific item to be +tempdata (it will be invalidated on the next HTTP request), so if you +intend to reuse that same key in the same request, you’d want to use +unset_tempdata():

+
$this->session->unset_tempdata('item');
+
+
+
+
+

Destroying a Session

+

To clear the current session (for example, during a logout), you may +simply use either PHP’s session_destroy() +function, or the sess_destroy() method. Both will work in exactly the +same way:

+
session_destroy();
+
+// or
+
+$this->session->sess_destroy();
+
+
+
+

Note

+

This must be the last session-related operation that you do +during the same request. All session data (including flashdata and +tempdata) will be destroyed permanently and functions will be +unusable during the same request after you destroy the session.

+
+
+
+

Accessing session metadata

+

In previous CodeIgniter versions, the session data array included 4 items +by default: ‘session_id’, ‘ip_address’, ‘user_agent’, ‘last_activity’.

+

This was due to the specifics of how sessions worked, but is now no longer +necessary with our new implementation. However, it may happen that your +application relied on these values, so here are alternative methods of +accessing them:

+
+
    +
  • session_id: session_id()
  • +
  • ip_address: $_SERVER['REMOTE_ADDR']
  • +
  • user_agent: $this->input->user_agent() (unused by sessions)
  • +
  • last_activity: Depends on the storage, no straightforward way. Sorry!
  • +
+
+
+
+

Session Preferences

+

CodeIgniter will usually make everything work out of the box. However, +Sessions are a very sensitive component of any application, so some +careful configuration must be done. Please take your time to consider +all of the options and their effects.

+

You’ll find the following Session related preferences in your +application/config/config.php file:

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefaultOptionsDescription
sess_driverfilesfiles/database/redis/memcached/customThe session storage driver to use.
sess_cookie_nameci_session[A-Za-z_-] characters onlyThe name used for the session cookie.
sess_expiration7200 (2 hours)Time in seconds (integer)The number of seconds you would like the session to last. +If you would like a non-expiring session (until browser is closed) set the value to zero: 0
sess_save_pathNULLNoneSpecifies the storage location, depends on the driver being used.
sess_match_ipFALSETRUE/FALSE (boolean)Whether to validate the user’s IP address when reading the session cookie. +Note that some ISPs dynamically changes the IP, so if you want a non-expiring session you +will likely set this to FALSE.
sess_time_to_update300Time in seconds (integer)This option controls how often the session class will regenerate itself and create a new +session ID. Setting it to 0 will disable session ID regeneration.
sess_regenerate_destroyFALSETRUE/FALSE (boolean)Whether to destroy session data associated with the old session ID when auto-regenerating +the session ID. When set to FALSE, the data will be later deleted by the garbage collector.
+
+

Note

+

As a last resort, the Session library will try to fetch PHP’s +session related INI settings, as well as legacy CI settings such as +‘sess_expire_on_close’ when any of the above is not configured. +However, you should never rely on this behavior as it can cause +unexpected results or be changed in the future. Please configure +everything properly.

+
+

In addition to the values above, the cookie and native drivers apply the +following configuration values shared by the Input and +Security classes:

+ +++++ + + + + + + + + + + + + + + + + + + + + +
PreferenceDefaultDescription
cookie_domain‘’The domain for which the session is applicable
cookie_path/The path to which the session is applicable
cookie_secureFALSEWhether to create the session cookie only on encrypted (HTTPS) connections
+
+

Note

+

The ‘cookie_httponly’ setting doesn’t have an effect on sessions. +Instead the HttpOnly parameter is always enabled, for security +reasons. Additionally, the ‘cookie_prefix’ setting is completely +ignored.

+
+
+
+

Session Drivers

+

As already mentioned, the Session library comes with 4 drivers, or storage +engines, that you can use:

+
+
    +
  • files
  • +
  • database
  • +
  • redis
  • +
  • memcached
  • +
+
+

By default, the Files Driver will be used when a session is initialized, +because it is the most safe choice and is expected to work everywhere +(virtually every environment has a file system).

+

However, any other driver may be selected via the $config['sess_driver'] +line in your application/config/config.php file, if you chose to do so. +Have it in mind though, every driver has different caveats, so be sure to +get yourself familiar with them (below) before you make that choice.

+

In addition, you may also create and use Custom Drivers, if the ones +provided by default don’t satisfy your use case.

+
+

Note

+

In previous CodeIgniter versions, a different, “cookie driver” +was the only option and we have received negative feedback on not +providing that option. While we do listen to feedback from the +community, we want to warn you that it was dropped because it is +unsafe and we advise you NOT to try to replicate it via a +custom driver.

+
+
+

Files Driver

+

The ‘files’ driver uses your file system for storing session data.

+

It can safely be said that it works exactly like PHP’s own default session +implementation, but in case this is an important detail for you, have it +mind that it is in fact not the same code and it has some limitations +(and advantages).

+

To be more specific, it doesn’t support PHP’s directory level and mode +formats used in session.save_path, +and it has most of the options hard-coded for safety. Instead, only +absolute paths are supported for $config['sess_save_path'].

+

Another important thing that you should know, is to make sure that you +don’t use a publicly-readable or shared directory for storing your session +files. Make sure that only you have access to see the contents of your +chosen sess_save_path directory. Otherwise, anybody who can do that, can +also steal any of the current sessions (also known as “session fixation” +attack).

+

On UNIX-like operating systems, this is usually achieved by setting the +0700 mode permissions on that directory via the chmod command, which +allows only the directory’s owner to perform read and write operations on +it. But be careful because the system user running the script is usually +not your own, but something like ‘www-data’ instead, so only setting those +permissions will probable break your application.

+

Instead, you should do something like this, depending on your environment

+
mkdir /<path to your application directory>/sessions/
+chmod 0700 /<path to your application directory>/sessions/
+chown www-data /<path to your application directory>/sessions/
+
+
+
+
Bonus Tip
+

Some of you will probably opt to choose another session driver because +file storage is usually slower. This is only half true.

+

A very basic test will probably trick you into believing that an SQL +database is faster, but in 99% of the cases, this is only true while you +only have a few current sessions. As the sessions count and server loads +increase - which is the time when it matters - the file system will +consistently outperform almost all relational database setups.

+

In addition, if performance is your only concern, you may want to look +into using tmpfs, +(warning: external resource), which can make your sessions blazing fast.

+
+
+
+

Database Driver

+

The ‘database’ driver uses a relational database such as MySQL or +PostgreSQL to store sessions. This is a popular choice among many users, +because it allows the developer easy access to the session data within +an application - it is just another table in your database.

+

However, there are some conditions that must be met:

+
+
    +
  • Only your default database connection (or the one that you access +as $this->db from your controllers) can be used.
  • +
  • You must have the Query Builder +enabled.
  • +
  • You can NOT use a persistent connection.
  • +
  • You can NOT use a connection with the cache_on setting enabled.
  • +
+
+

In order to use the ‘database’ session driver, you must also create this +table that we already mentioned and then set it as your +$config['sess_save_path'] value. +For example, if you would like to use ‘ci_sessions’ as your table name, +you would do this:

+
$config['sess_driver'] = 'database';
+$config['sess_save_path'] = 'ci_sessions';
+
+
+
+

Note

+

If you’ve upgraded from a previous version of CodeIgniter and +you don’t have ‘sess_save_path’ configured, then the Session +library will look for the old ‘sess_table_name’ setting and use +it instead. Please don’t rely on this behavior as it will get +removed in the future.

+
+

And then of course, create the database table …

+

For MySQL:

+
CREATE TABLE IF NOT EXISTS `ci_sessions` (
+        `id` varchar(128) NOT NULL,
+        `ip_address` varchar(45) NOT NULL,
+        `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
+        `data` blob NOT NULL,
+        KEY `ci_sessions_timestamp` (`timestamp`)
+);
+
+
+

For PostgreSQL:

+
CREATE TABLE "ci_sessions" (
+        "id" varchar(128) NOT NULL,
+        "ip_address" varchar(45) NOT NULL,
+        "timestamp" bigint DEFAULT 0 NOT NULL,
+        "data" text DEFAULT '' NOT NULL
+);
+
+CREATE INDEX "ci_sessions_timestamp" ON "ci_sessions" ("timestamp");
+
+
+

You will also need to add a PRIMARY KEY depending on your ‘sess_match_ip’ +setting. The examples below work both on MySQL and PostgreSQL:

+
// When sess_match_ip = TRUE
+ALTER TABLE ci_sessions ADD PRIMARY KEY (id, ip_address);
+
+// When sess_match_ip = FALSE
+ALTER TABLE ci_sessions ADD PRIMARY KEY (id);
+
+// To drop a previously created primary key (use when changing the setting)
+ALTER TABLE ci_sessions DROP PRIMARY KEY;
+
+
+
+

Important

+

Only MySQL and PostgreSQL databases are officially +supported, due to lack of advisory locking mechanisms on other +platforms. Using sessions without locks can cause all sorts of +problems, especially with heavy usage of AJAX, and we will not +support such cases. Use session_write_close() after you’ve +done processing session data if you’re having performance +issues.

+
+
+
+

Redis Driver

+
+

Note

+

Since Redis doesn’t have a locking mechanism exposed, locks for +this driver are emulated by a separate value that is kept for up +to 300 seconds.

+
+

Redis is a storage engine typically used for caching and popular because +of its high performance, which is also probably your reason to use the +‘redis’ session driver.

+

The downside is that it is not as ubiquitous as relational databases and +requires the phpredis PHP +extension to be installed on your system, and that one doesn’t come +bundled with PHP. +Chances are, you’re only be using the ‘redis’ driver only if you’re already +both familiar with Redis and using it for other purposes.

+

Just as with the ‘files’ and ‘database’ drivers, you must also configure +the storage location for your sessions via the +$config['sess_save_path'] setting. +The format here is a bit different and complicated at the same time. It is +best explained by the phpredis extension’s README file, so we’ll simply +link you to it:

+
+
+
+

Warning

+

CodeIgniter’s Session library does NOT use the actual ‘redis’ +session.save_handler. Take note only of the path format in +the link above.

+
+

For the most common case however, a simple host:port pair should be +sufficient:

+
$config['sess_driver'] = 'redis';
+$config['sess_save_path'] = 'tcp://localhost:6379';
+
+
+
+
+

Memcached Driver

+
+

Note

+

Since Memcache doesn’t have a locking mechanism exposed, locks +for this driver are emulated by a separate value that is kept for +up to 300 seconds.

+
+

The ‘memcached’ driver is very similar to the ‘redis’ one in all of its +properties, except perhaps for availability, because PHP’s Memcached extension is distributed via PECL and some +Linux distrubutions make it available as an easy to install package.

+

Other than that, and without any intentional bias towards Redis, there’s +not much different to be said about Memcached - it is also a popular +product that is usually used for caching and famed for its speed.

+

However, it is worth noting that the only guarantee given by Memcached +is that setting value X to expire after Y seconds will result in it being +deleted after Y seconds have passed (but not necessarily that it won’t +expire earlier than that time). This happens very rarely, but should be +considered as it may result in loss of sessions.

+

The $config['sess_save_path'] format is fairly straightforward here, +being just a host:port pair:

+
$config['sess_driver'] = 'memcached';
+$config['sess_save_path'] = 'localhost:11211';
+
+
+
+
Bonus Tip
+

Multi-server configuration with an optional weight parameter as the +third colon-separated (:weight) value is also supported, but we have +to note that we haven’t tested if that is reliable.

+

If you want to experiment with this feature (on your own risk), simply +separate the multiple server paths with commas:

+
// localhost will be given higher priority (5) here,
+// compared to 192.0.2.1 with a weight of 1.
+$config['sess_save_path'] = 'localhost:11211:5,192.0.2.1:11211:1';
+
+
+
+
+
+

Custom Drivers

+

You may also create your own, custom session drivers. However, have it in +mind that this is typically not an easy task, as it takes a lot of +knowledge to do it properly.

+

You need to know not only how sessions work in general, but also how they +work specifically in PHP, how the underlying storage mechanism works, how +to handle concurrency, avoid deadlocks (but NOT through lack of locks) and +last but not least - how to handle the potential security issues, which +is far from trivial.

+

Long story short - if you don’t know how to do that already in raw PHP, +you shouldn’t be trying to do it within CodeIgniter either. You’ve been +warned.

+

If you only want to add some extra functionality to your sessions, just +extend the base Session class, which is a lot more easier. Read the +Creating Libraries article to +learn how to do that.

+

Now, to the point - there are three general rules that you must follow +when creating a session driver for CodeIgniter:

+
+
    +
  • Put your driver’s file under application/libraries/Session/drivers/ +and follow the naming conventions used by the Session class.

    +

    For example, if you were to create a ‘dummy’ driver, you would have +a Session_dummy_driver class name, that is declared in +application/libraries/Session/drivers/Session_dummy_driver.php.

    +
  • +
  • Extend the CI_Session_driver class.

    +

    This is just a basic class with a few internal helper methods. It is +also extendable like any other library, if you really need to do that, +but we are not going to explain how … if you’re familiar with how +class extensions/overrides work in CI, then you already know how to do +it. If not, well, you shouldn’t be doing it in the first place.

    +
  • +
  • Implement the SessionHandlerInterface interface.

    +
    +

    Note

    +

    You may notice that SessionHandlerInterface is provided +by PHP since version 5.4.0. CodeIgniter will automatically declare +the same interface if you’re running an older PHP version.

    +
    +

    The link will explain why and how.

    +
  • +
+
+

So, based on our ‘dummy’ driver example above, you’d end up with something +like this:

+
// application/libraries/Session/drivers/Session_dummy_driver.php:
+
+class CI_Session_dummy_driver extends CI_Session_driver implements SessionHandlerInterface
+{
+
+        public function __construct(&$params)
+        {
+                // DO NOT forget this
+                parent::__construct($params);
+
+                // Configuration & other initializations
+        }
+
+        public function open($save_path, $name)
+        {
+                // Initialize storage mechanism (connection)
+        }
+
+        public function read($session_id)
+        {
+                // Read session data (if exists), acquire locks
+        }
+
+        public function write($session_id, $session_data)
+        {
+                // Create / update session data (it might not exist!)
+        }
+
+        public function close()
+        {
+                // Free locks, close connections / streams / etc.
+        }
+
+        public function destroy($session_id)
+        {
+                // Call close() method & destroy data for current session (order may differ)
+        }
+
+        public function gc($maxlifetime)
+        {
+                // Erase data for expired sessions
+        }
+
+}
+
+
+

If you’ve done everything properly, you can now set your sess_driver +configuration value to ‘dummy’ and use your own driver. Congratulations!

+
+
+
+
+

Class Reference

+
+
+class CI_Session
+
+
+userdata([$key = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (mixed) – Session item key or NULL
  • +
+
Returns:

Value of the specified item key, or an array of all userdata

+
Return type:

mixed

+
+

Gets the value for a specific $_SESSION item, or an +array of all “userdata” items if not key was specified.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications. You should +directly access $_SESSION instead.

+
+
+ +
+
+all_userdata()
+
+++ + + + + + +
Returns:An array of all userdata
Return type:array
+

Returns an array containing all “userdata” items.

+
+

Note

+

This method is DEPRECATED. Use userdata() +with no parameters instead.

+
+
+ +
+
+&get_userdata()
+
+++ + + + + + +
Returns:A reference to $_SESSION
Return type:array
+

Returns a reference to the $_SESSION array.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications.

+
+
+ +
+
+has_userdata($key)
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Session item key
  • +
+
Returns:

TRUE if the specified key exists, FALSE if not

+
Return type:

bool

+
+

Checks if an item exists in $_SESSION.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications. It is just +an alias for isset($_SESSION[$key]) - please +use that instead.

+
+
+ +
+
+set_userdata($data[, $value = NULL])
+
+++ + + + + + +
Parameters:
    +
  • $data (mixed) – An array of key/value pairs to set as session data, or the key for a single item
  • +
  • $value (mixed) – The value to set for a specific session item, if $data is a key
  • +
+
Return type:

void

+
+

Assigns data to the $_SESSION superglobal.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications.

+
+
+ +
+
+unset_userdata($key)
+
+++ + + + + + +
Parameters:
    +
  • $key (mixed) – Key for the session data item to unset, or an array of multiple keys
  • +
+
Return type:

void

+
+

Unsets the specified key(s) from the $_SESSION +superglobal.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications. It is just +an alias for unset($_SESSION[$key]) - please +use that instead.

+
+
+ +
+
+mark_as_flash($key)
+
+++ + + + + + + + +
Parameters:
    +
  • $key (mixed) – Key to mark as flashdata, or an array of multiple keys
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Marks a $_SESSION item key (or multiple ones) as +“flashdata”.

+
+ +
+
+get_flash_keys()
+
+++ + + + + + +
Returns:Array containing the keys of all “flashdata” items.
Return type:array
+

Gets a list of all $_SESSION that have been marked as +“flashdata”.

+
+ +
+
+unmark_flash($key)
+
+++ + + + + + +
Parameters:
    +
  • $key (mixed) – Key to be un-marked as flashdata, or an array of multiple keys
  • +
+
Return type:

void

+
+

Unmarks a $_SESSION item key (or multiple ones) as +“flashdata”.

+
+ +
+
+flashdata([$key = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (mixed) – Flashdata item key or NULL
  • +
+
Returns:

Value of the specified item key, or an array of all flashdata

+
Return type:

mixed

+
+

Gets the value for a specific $_SESSION item that has +been marked as “flashdata”, or an array of all “flashdata” +items if no key was specified.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications. You should +directly access $_SESSION instead.

+
+
+ +
+
+keep_flashdata($key)
+
+++ + + + + + + + +
Parameters:
    +
  • $key (mixed) – Flashdata key to keep, or an array of multiple keys
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Retains the specified session data key(s) as “flashdata” +through the next request.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications. It is just +an alias for the mark_as_flash() method.

+
+
+ +
+
+set_flashdata($data[, $value = NULL])
+
+++ + + + + + +
Parameters:
    +
  • $data (mixed) – An array of key/value pairs to set as flashdata, or the key for a single item
  • +
  • $value (mixed) – The value to set for a specific session item, if $data is a key
  • +
+
Return type:

void

+
+

Assigns data to the $_SESSION superglobal and marks it +as “flashdata”.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications.

+
+
+ +
+
+mark_as_temp($key[, $ttl = 300])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (mixed) – Key to mark as tempdata, or an array of multiple keys
  • +
  • $ttl (int) – Time-to-live value for the tempdata, in seconds
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Marks a $_SESSION item key (or multiple ones) as +“tempdata”.

+
+ +
+
+get_temp_keys()
+
+++ + + + + + +
Returns:Array containing the keys of all “tempdata” items.
Return type:array
+

Gets a list of all $_SESSION that have been marked as +“tempdata”.

+
+ +
+
+unmark_temp($key)
+
+++ + + + + + +
Parameters:
    +
  • $key (mixed) – Key to be un-marked as tempdata, or an array of multiple keys
  • +
+
Return type:

void

+
+

Unmarks a $_SESSION item key (or multiple ones) as +“tempdata”.

+
+ +
+
+tempdata([$key = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (mixed) – Tempdata item key or NULL
  • +
+
Returns:

Value of the specified item key, or an array of all tempdata

+
Return type:

mixed

+
+

Gets the value for a specific $_SESSION item that has +been marked as “tempdata”, or an array of all “tempdata” +items if no key was specified.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications. You should +directly access $_SESSION instead.

+
+
+ +
+
+set_tempdata($data[, $value = NULL])
+
+++ + + + + + +
Parameters:
    +
  • $data (mixed) – An array of key/value pairs to set as tempdata, or the key for a single item
  • +
  • $value (mixed) – The value to set for a specific session item, if $data is a key
  • +
  • $ttl (int) – Time-to-live value for the tempdata item(s), in seconds
  • +
+
Return type:

void

+
+

Assigns data to the $_SESSION superglobal and marks it +as “tempdata”.

+
+

Note

+

This is a legacy method kept only for backwards +compatibility with older applications.

+
+
+ +
+
+sess_regenerate([$destroy = FALSE])
+
+++ + + + + + +
Parameters:
    +
  • $destroy (bool) – Whether to destroy session data
  • +
+
Return type:

void

+
+

Regenerate session ID, optionally destroying the current +session’s data.

+
+

Note

+

This method is just an alias for PHP’s native +session_regenerate_id() function.

+
+
+ +
+
+sess_destroy()
+
+++ + + + +
Return type:void
+

Destroys the current session.

+
+

Note

+

This must be the last session-related function +that you call. All session data will be lost after +you do that.

+
+
+

Note

+

This method is just an alias for PHP’s native +session_destroy() function.

+
+
+ +
+
+__get($key)
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Session item key
  • +
+
Returns:

The requested session data item, or NULL if it doesn’t exist

+
Return type:

mixed

+
+

A magic method that allows you to use +$this->session->item instead of $_SESSION['item'], +if that’s what you prefer.

+

It will also return the session ID by calling +session_id() if you try to access +$this->session->session_id.

+
+ +
+
+__set($key, $value)
+
+++ + + + + + +
Parameters:
    +
  • $key (string) – Session item key
  • +
  • $value (mixed) – Value to assign to the session item key
  • +
+
Returns:

void

+
+

A magic method that allows you to assign items to +$_SESSION by accessing them as $this->session +properties:

+
$this->session->foo = 'bar';
+
+// Results in:
+// $_SESSION['foo'] = 'bar';
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/table.html b/user_guide/libraries/table.html new file mode 100644 index 000000000..7882e5ba0 --- /dev/null +++ b/user_guide/libraries/table.html @@ -0,0 +1,911 @@ + + + + + + + + + + HTML Table Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

HTML Table Class

+

The Table Class provides functions that enable you to auto-generate HTML +tables from arrays or database result sets.

+ +
+

Using the Table Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Table class is initialized +in your controller using the $this->load->library() method:

+
$this->load->library('table');
+
+
+

Once loaded, the Table library object will be available using:

+
$this->table
+
+
+
+
+

Examples

+

Here is an example showing how you can create a table from a +multi-dimensional array. Note that the first array index will become the +table heading (or you can set your own headings using the set_heading() +method described in the function reference below).

+
$this->load->library('table');
+
+$data = array(
+        array('Name', 'Color', 'Size'),
+        array('Fred', 'Blue', 'Small'),
+        array('Mary', 'Red', 'Large'),
+        array('John', 'Green', 'Medium')
+);
+
+echo $this->table->generate($data);
+
+
+

Here is an example of a table created from a database query result. The +table class will automatically generate the headings based on the table +names (or you can set your own headings using the set_heading() +method described in the class reference below).

+
$this->load->library('table');
+
+$query = $this->db->query('SELECT * FROM my_table');
+
+echo $this->table->generate($query);
+
+
+

Here is an example showing how you might create a table using discrete +parameters:

+
$this->load->library('table');
+
+$this->table->set_heading('Name', 'Color', 'Size');
+
+$this->table->add_row('Fred', 'Blue', 'Small');
+$this->table->add_row('Mary', 'Red', 'Large');
+$this->table->add_row('John', 'Green', 'Medium');
+
+echo $this->table->generate();
+
+
+

Here is the same example, except instead of individual parameters, +arrays are used:

+
$this->load->library('table');
+
+$this->table->set_heading(array('Name', 'Color', 'Size'));
+
+$this->table->add_row(array('Fred', 'Blue', 'Small'));
+$this->table->add_row(array('Mary', 'Red', 'Large'));
+$this->table->add_row(array('John', 'Green', 'Medium'));
+
+echo $this->table->generate();
+
+
+
+
+

Changing the Look of Your Table

+

The Table Class permits you to set a table template with which you can +specify the design of your layout. Here is the template prototype:

+
$template = array(
+        'table_open'            => '<table border="0" cellpadding="4" cellspacing="0">',
+
+        'thead_open'            => '<thead>',
+        'thead_close'           => '</thead>',
+
+        'heading_row_start'     => '<tr>',
+        'heading_row_end'       => '</tr>',
+        'heading_cell_start'    => '<th>',
+        'heading_cell_end'      => '</th>',
+
+        'tbody_open'            => '<tbody>',
+        'tbody_close'           => '</tbody>',
+
+        'row_start'             => '<tr>',
+        'row_end'               => '</tr>',
+        'cell_start'            => '<td>',
+        'cell_end'              => '</td>',
+
+        'row_alt_start'         => '<tr>',
+        'row_alt_end'           => '</tr>',
+        'cell_alt_start'        => '<td>',
+        'cell_alt_end'          => '</td>',
+
+        'table_close'           => '</table>'
+);
+
+$this->table->set_template($template);
+
+
+
+

Note

+

You’ll notice there are two sets of “row” blocks in the +template. These permit you to create alternating row colors or design +elements that alternate with each iteration of the row data.

+
+

You are NOT required to submit a complete template. If you only need to +change parts of the layout you can simply submit those elements. In this +example, only the table opening tag is being changed:

+
$template = array(
+        'table_open' => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">'
+);
+
+$this->table->set_template($template);
+
+
+

You can also set defaults for these in a config file.

+
+
+
+

Class Reference

+
+
+class CI_Table
+
+
+$function = NULL
+

Allows you to specify a native PHP function or a valid function array object to be applied to all cell data.

+
$this->load->library('table');
+
+$this->table->set_heading('Name', 'Color', 'Size');
+$this->table->add_row('Fred', '<strong>Blue</strong>', 'Small');
+
+$this->table->function = 'htmlspecialchars';
+echo $this->table->generate();
+
+
+

In the above example, all cell data would be ran through PHP’s htmlspecialchars() function, resulting in:

+
<td>Fred</td><td>&lt;strong&gt;Blue&lt;/strong&gt;</td><td>Small</td>
+
+
+
+ +
+
+generate([$table_data = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $table_data (mixed) – Data to populate the table rows with
  • +
+
Returns:

HTML table

+
Return type:

string

+
+

Returns a string containing the generated table. Accepts an optional parameter which can be an array or a database result object.

+
+ +
+
+set_caption($caption)
+
+++ + + + + + + + +
Parameters:
    +
  • $caption (string) – Table caption
  • +
+
Returns:

CI_Table instance (method chaining)

+
Return type:

CI_Table

+
+

Permits you to add a caption to the table.

+
$this->table->set_caption('Colors');
+
+
+
+ +
+
+set_heading([$args = array()[, ...]])
+
+++ + + + + + + + +
Parameters:
    +
  • $args (mixed) – An array or multiple strings containing the table column titles
  • +
+
Returns:

CI_Table instance (method chaining)

+
Return type:

CI_Table

+
+

Permits you to set the table heading. You can submit an array or discrete params:

+
$this->table->set_heading('Name', 'Color', 'Size');
+
+$this->table->set_heading(array('Name', 'Color', 'Size'));
+
+
+
+ +
+
+add_row([$args = array()[, ...]])
+
+++ + + + + + + + +
Parameters:
    +
  • $args (mixed) – An array or multiple strings containing the row values
  • +
+
Returns:

CI_Table instance (method chaining)

+
Return type:

CI_Table

+
+

Permits you to add a row to your table. You can submit an array or discrete params:

+
$this->table->add_row('Blue', 'Red', 'Green');
+
+$this->table->add_row(array('Blue', 'Red', 'Green'));
+
+
+

If you would like to set an individual cell’s tag attributes, you can use an associative array for that cell. +The associative key data defines the cell’s data. Any other key => val pairs are added as key=’val’ attributes to the tag:

+
$cell = array('data' => 'Blue', 'class' => 'highlight', 'colspan' => 2);
+$this->table->add_row($cell, 'Red', 'Green');
+
+// generates
+// <td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td>
+
+
+
+ +
+
+make_columns([$array = array()[, $col_limit = 0]])
+
+++ + + + + + + + +
Parameters:
    +
  • $array (array) – An array containing multiple rows’ data
  • +
  • $col_limit (int) – Count of columns in the table
  • +
+
Returns:

An array of HTML table columns

+
Return type:

array

+
+

This method takes a one-dimensional array as input and creates a multi-dimensional array with a depth equal to the number of columns desired. +This allows a single array with many elements to be displayed in a table that has a fixed column count. Consider this example:

+
$list = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve');
+
+$new_list = $this->table->make_columns($list, 3);
+
+$this->table->generate($new_list);
+
+// Generates a table with this prototype
+
+<table border="0" cellpadding="4" cellspacing="0">
+<tr>
+<td>one</td><td>two</td><td>three</td>
+</tr><tr>
+<td>four</td><td>five</td><td>six</td>
+</tr><tr>
+<td>seven</td><td>eight</td><td>nine</td>
+</tr><tr>
+<td>ten</td><td>eleven</td><td>twelve</td></tr>
+</table>
+
+
+
+ +
+
+set_template($template)
+
+++ + + + + + + + +
Parameters:
    +
  • $template (array) – An associative array containing template values
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Permits you to set your template. You can submit a full or partial template.

+
$template = array(
+        'table_open'  => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">'
+);
+
+$this->table->set_template($template);
+
+
+
+ +
+
+set_empty($value)
+
+++ + + + + + + + +
Parameters:
    +
  • $value (mixed) – Value to put in empty cells
  • +
+
Returns:

CI_Table instance (method chaining)

+
Return type:

CI_Table

+
+

Lets you set a default value for use in any table cells that are empty. +You might, for example, set a non-breaking space:

+
$this->table->set_empty("&nbsp;");
+
+
+
+ +
+
+clear()
+
+++ + + + + + +
Returns:CI_Table instance (method chaining)
Return type:CI_Table
+

Lets you clear the table heading and row data. If you need to show multiple tables with different data you should to call this method +after each table has been generated to clear the previous table information. Example:

+
$this->load->library('table');
+
+$this->table->set_heading('Name', 'Color', 'Size');
+$this->table->add_row('Fred', 'Blue', 'Small');
+$this->table->add_row('Mary', 'Red', 'Large');
+$this->table->add_row('John', 'Green', 'Medium');
+
+echo $this->table->generate();
+
+$this->table->clear();
+
+$this->table->set_heading('Name', 'Day', 'Delivery');
+$this->table->add_row('Fred', 'Wednesday', 'Express');
+$this->table->add_row('Mary', 'Monday', 'Air');
+$this->table->add_row('John', 'Saturday', 'Overnight');
+
+echo $this->table->generate();
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/trackback.html b/user_guide/libraries/trackback.html new file mode 100644 index 000000000..6617374d6 --- /dev/null +++ b/user_guide/libraries/trackback.html @@ -0,0 +1,1035 @@ + + + + + + + + + + Trackback Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Trackback Class

+

The Trackback Class provides functions that enable you to send and +receive Trackback data.

+

If you are not familiar with Trackbacks you’ll find more information +here.

+ +
+

Using the Trackback Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Trackback class is +initialized in your controller using the $this->load->library() method:

+
$this->load->library('trackback');
+
+
+

Once loaded, the Trackback library object will be available using:

+
$this->trackback
+
+
+
+
+

Sending Trackbacks

+

A Trackback can be sent from any of your controller functions using code +similar to this example:

+
$this->load->library('trackback');
+
+$tb_data = array(
+        'ping_url'  => 'http://example.com/trackback/456',
+        'url'       => 'http://www.my-example.com/blog/entry/123',
+        'title'     => 'The Title of My Entry',
+        'excerpt'   => 'The entry content.',
+        'blog_name' => 'My Blog Name',
+        'charset'   => 'utf-8'
+);
+
+if ( ! $this->trackback->send($tb_data))
+{
+        echo $this->trackback->display_errors();
+}
+else
+{
+        echo 'Trackback was sent!';
+}
+
+
+

Description of array data:

+
    +
  • ping_url - The URL of the site you are sending the Trackback to. +You can send Trackbacks to multiple URLs by separating each URL with a comma.
  • +
  • url - The URL to YOUR site where the weblog entry can be seen.
  • +
  • title - The title of your weblog entry.
  • +
  • excerpt - The content of your weblog entry.
  • +
  • blog_name - The name of your weblog.
  • +
  • charset - The character encoding your weblog is written in. If omitted, UTF-8 will be used.
  • +
+
+

Note

+

The Trackback class will automatically send only the first 500 characters of your +entry. It will also strip all HTML.

+
+

The Trackback sending method returns TRUE/FALSE (boolean) on success +or failure. If it fails, you can retrieve the error message using:

+
$this->trackback->display_errors();
+
+
+
+
+

Receiving Trackbacks

+

Before you can receive Trackbacks you must create a weblog. If you don’t +have a blog yet there’s no point in continuing.

+

Receiving Trackbacks is a little more complex than sending them, only +because you will need a database table in which to store them, and you +will need to validate the incoming trackback data. You are encouraged to +implement a thorough validation process to guard against spam and +duplicate data. You may also want to limit the number of Trackbacks you +allow from a particular IP within a given span of time to further +curtail spam. The process of receiving a Trackback is quite simple; the +validation is what takes most of the effort.

+
+
+

Your Ping URL

+

In order to accept Trackbacks you must display a Trackback URL next to +each one of your weblog entries. This will be the URL that people will +use to send you Trackbacks (we will refer to this as your “Ping URL”).

+

Your Ping URL must point to a controller function where your Trackback +receiving code is located, and the URL must contain the ID number for +each particular entry, so that when the Trackback is received you’ll be +able to associate it with a particular entry.

+

For example, if your controller class is called Trackback, and the +receiving function is called receive, your Ping URLs will look something +like this:

+
http://example.com/index.php/trackback/receive/entry_id
+
+
+

Where entry_id represents the individual ID number for each of your +entries.

+
+
+

Creating a Trackback Table

+

Before you can receive Trackbacks you must create a table in which to +store them. Here is a basic prototype for such a table:

+
CREATE TABLE trackbacks (
+        tb_id int(10) unsigned NOT NULL auto_increment,
+        entry_id int(10) unsigned NOT NULL default 0,
+        url varchar(200) NOT NULL,
+        title varchar(100) NOT NULL,
+        excerpt text NOT NULL,
+        blog_name varchar(100) NOT NULL,
+        tb_date int(10) NOT NULL,
+        ip_address varchar(45) NOT NULL,
+        PRIMARY KEY `tb_id` (`tb_id`),
+        KEY `entry_id` (`entry_id`)
+);
+
+
+

The Trackback specification only requires four pieces of information to +be sent in a Trackback (url, title, excerpt, blog_name), but to make +the data more useful we’ve added a few more fields in the above table +schema (date, IP address, etc.).

+
+
+

Processing a Trackback

+

Here is an example showing how you will receive and process a Trackback. +The following code is intended for use within the controller function +where you expect to receive Trackbacks.:

+
$this->load->library('trackback');
+$this->load->database();
+
+if ($this->uri->segment(3) == FALSE)
+{
+        $this->trackback->send_error('Unable to determine the entry ID');
+}
+
+if ( ! $this->trackback->receive())
+{
+        $this->trackback->send_error('The Trackback did not contain valid data');
+}
+
+$data = array(
+        'tb_id'      => '',
+        'entry_id'   => $this->uri->segment(3),
+        'url'        => $this->trackback->data('url'),
+        'title'      => $this->trackback->data('title'),
+        'excerpt'    => $this->trackback->data('excerpt'),
+        'blog_name'  => $this->trackback->data('blog_name'),
+        'tb_date'    => time(),
+        'ip_address' => $this->input->ip_address()
+);
+
+$sql = $this->db->insert_string('trackbacks', $data);
+$this->db->query($sql);
+
+$this->trackback->send_success();
+
+
+
+

Notes:

+

The entry ID number is expected in the third segment of your URL. This +is based on the URI example we gave earlier:

+
http://example.com/index.php/trackback/receive/entry_id
+
+
+

Notice the entry_id is in the third URI segment, which you can retrieve +using:

+
$this->uri->segment(3);
+
+
+

In our Trackback receiving code above, if the third segment is missing, +we will issue an error. Without a valid entry ID, there’s no reason to +continue.

+

The $this->trackback->receive() function is simply a validation function +that looks at the incoming data and makes sure it contains the four +pieces of data that are required (url, title, excerpt, blog_name). It +returns TRUE on success and FALSE on failure. If it fails you will issue +an error message.

+

The incoming Trackback data can be retrieved using this function:

+
$this->trackback->data('item')
+
+
+

Where item represents one of these four pieces of info: url, title, +excerpt, or blog_name

+

If the Trackback data is successfully received, you will issue a success +message using:

+
$this->trackback->send_success();
+
+
+
+

Note

+

The above code contains no data validation, which you are +encouraged to add.

+
+
+
+
+
+

Class Reference

+
+
+class CI_Trackback
+
+
+$data = array('url' => '', 'title' => '', 'excerpt' => '', 'blog_name' => '', 'charset' => '')
+

Trackback data array.

+
+ +
+
+$convert_ascii = TRUE
+

Whether to convert high ASCII and MS Word characters to HTML entities.

+
+ +
+
+send($tb_data)
+
+++ + + + + + + + +
Parameters:
    +
  • $tb_data (array) – Trackback data
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Send trackback.

+
+ +
+
+receive()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

This method simply validates the incoming TB data, returning TRUE on success and FALSE on failure. +If the data is valid it is set to the $this->data array so that it can be inserted into a database.

+
+ +
+
+send_error([$message = 'Incomplete information'])
+
+++ + + + + + +
Parameters:
    +
  • $message (string) – Error message
  • +
+
Return type:

void

+
+

Responses to a trackback request with an error message.

+
+

Note

+

This method will terminate script execution.

+
+
+ +
+
+send_success()
+
+++ + + + +
Return type:void
+

Responses to a trackback request with a success message.

+
+

Note

+

This method will terminate script execution.

+
+
+ +
+
+data($item)
+
+++ + + + + + + + +
Parameters:
    +
  • $item (string) – Data key
  • +
+
Returns:

Data value or empty string if not found

+
Return type:

string

+
+

Returns a single item from the response data array.

+
+ +
+
+process($url, $data)
+
+++ + + + + + + + +
Parameters:
    +
  • $url (string) – Target url
  • +
  • $data (string) – Raw POST data
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Opens a socket connection and passes the data to the server, returning TRUE on success and FALSE on failure.

+
+ +
+
+extract_urls($urls)
+
+++ + + + + + + + +
Parameters:
    +
  • $urls (string) – Comma-separated URL list
  • +
+
Returns:

Array of URLs

+
Return type:

array

+
+

This method lets multiple trackbacks to be sent. It takes a string of URLs (separated by comma or space) and puts each URL into an array.

+
+ +
+
+validate_url(&$url)
+
+++ + + + + + +
Parameters:
    +
  • $url (string) – Trackback URL
  • +
+
Return type:

void

+
+

Simply adds the http:// prefix it it’s not already present in the URL.

+
+ +
+
+get_id($url)
+
+++ + + + + + + + +
Parameters:
    +
  • $url (string) – Trackback URL
  • +
+
Returns:

URL ID or FALSE on failure

+
Return type:

string

+
+

Find and return a trackback URL’s ID or FALSE on failure.

+
+ +
+
+convert_xml($str)
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
+
Returns:

Converted string

+
Return type:

string

+
+

Converts reserved XML characters to entities.

+
+ +
+
+limit_characters($str[, $n = 500[, $end_char = '&#8230;']])
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
  • $n (int) – Max characters number
  • +
  • $end_char (string) – Character to put at end of string
  • +
+
Returns:

Shortened string

+
Return type:

string

+
+

Limits the string based on the character count. Will preserve complete words.

+
+ +
+
+convert_ascii($str)
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
+
Returns:

Converted string

+
Return type:

string

+
+

Converts high ASCII text and MS Word special characterss to HTML entities.

+
+ +
+
+set_error($msg)
+
+++ + + + + + +
Parameters:
    +
  • $msg (string) – Error message
  • +
+
Return type:

void

+
+

Set an log an error message.

+
+ +
+
+display_errors([$open = '<p>'[, $close = '</p>']])
+
+++ + + + + + + + +
Parameters:
    +
  • $open (string) – Open tag
  • +
  • $close (string) – Close tag
  • +
+
Returns:

HTML formatted error messages

+
Return type:

string

+
+

Returns error messages formatted in HTML or an empty string if there are no errors.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/typography.html b/user_guide/libraries/typography.html new file mode 100644 index 000000000..e0875d6a1 --- /dev/null +++ b/user_guide/libraries/typography.html @@ -0,0 +1,657 @@ + + + + + + + + + + Typography Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

Typography Class

+

The Typography Class provides methods that help you format text.

+ +
+

Using the Typography Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Typography class is +initialized in your controller using the $this->load->library() method:

+
$this->load->library('typography');
+
+
+

Once loaded, the Typography library object will be available using:

+
$this->typography
+
+
+
+
+
+

Class Reference

+
+
+class CI_Typography
+
+
+$protect_braced_quotes = FALSE
+

When using the Typography library in conjunction with the Template Parser library +it can often be desirable to protect single and double quotes within curly braces. +To enable this, set the protect_braced_quotes class property to TRUE.

+

Usage example:

+
$this->load->library('typography');
+$this->typography->protect_braced_quotes = TRUE;
+
+
+
+ +
+
+auto_typography($str[, $reduce_linebreaks = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
  • $reduce_linebreaks (bool) – Whether to reduce consequitive linebreaks
  • +
+
Returns:

HTML typography-safe string

+
Return type:

string

+
+

Formats text so that it is semantically and typographically correct HTML. +Takes a string as input and returns it with the following formatting:

+
+
    +
  • Surrounds paragraphs within <p></p> (looks for double line breaks to identify paragraphs).
  • +
  • Single line breaks are converted to <br />, except those that appear within <pre> tags.
  • +
  • Block level elements, like <div> tags, are not wrapped within paragraphs, but their contained text is if it contains paragraphs.
  • +
  • Quotes are converted to correctly facing curly quote entities, except those that appear within tags.
  • +
  • Apostrophes are converted to curly apostrophe entities.
  • +
  • Double dashes (either like – this or like–this) are converted to em—dashes.
  • +
  • Three consecutive periods either preceding or following a word are converted to ellipsis (…).
  • +
  • Double spaces following sentences are converted to non-breaking spaces to mimic double spacing.
  • +
+
+

Usage example:

+
$string = $this->typography->auto_typography($string);
+
+
+

There is one optional parameter that determines whether the parser should reduce more than two consecutive line breaks down to two. +Pass boolean TRUE to enable reducing line breaks:

+
$string = $this->typography->auto_typography($string, TRUE);
+
+
+
+

Note

+

Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. +If you choose to use this method you may want to consider caching your pages.

+
+
+ +
+
+format_characters($str)
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
+
Returns:

Formatted string

+
Return type:

string

+
+

This method is similar to auto_typography() above, except that it only does character conversion:

+
+
    +
  • Quotes are converted to correctly facing curly quote entities, except those that appear within tags.
  • +
  • Apostrophes are converted to curly apostrophe entities.
  • +
  • Double dashes (either like – this or like–this) are converted to em—dashes.
  • +
  • Three consecutive periods either preceding or following a word are converted to ellipsis (…).
  • +
  • Double spaces following sentences are converted to non-breaking spaces to mimic double spacing.
  • +
+
+

Usage example:

+
$string = $this->typography->format_characters($string);
+
+
+
+ +
+
+nl2br_except_pre($str)
+
+++ + + + + + + + +
Parameters:
    +
  • $str (string) – Input string
  • +
+
Returns:

Formatted string

+
Return type:

string

+
+

Converts newlines to <br /> tags unless they appear within <pre> tags. +This method is identical to the native PHP nl2br() function, except that it ignores <pre> tags.

+

Usage example:

+
$string = $this->typography->nl2br_except_pre($string);
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/unit_testing.html b/user_guide/libraries/unit_testing.html new file mode 100644 index 000000000..f30229cb8 --- /dev/null +++ b/user_guide/libraries/unit_testing.html @@ -0,0 +1,846 @@ + + + + + + + + + + Unit Testing Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Unit Testing Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Unit Testing Class

+

Unit testing is an approach to software development in which tests are +written for each function in your application. If you are not familiar +with the concept you might do a little googling on the subject.

+

CodeIgniter’s Unit Test class is quite simple, consisting of an +evaluation function and two result functions. It’s not intended to be a +full-blown test suite but rather a simple mechanism to evaluate your +code to determine if it is producing the correct data type and result.

+ +
+

Using the Unit Testing Library

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Unit Test class is +initialized in your controller using the $this->load->library function:

+
$this->load->library('unit_test');
+
+
+

Once loaded, the Unit Test object will be available using $this->unit

+
+
+

Running Tests

+

Running a test involves supplying a test and an expected result in the +following way:

+
+
$this->unit->run(‘test’, ‘expected result’, ‘test name’, ‘notes’);
+

Where test is the result of the code you wish to test, expected result +is the data type you expect, test name is an optional name you can give +your test, and notes are optional notes. Example:

+
$test = 1 + 1;
+
+$expected_result = 2;
+
+$test_name = 'Adds one plus one';
+
+$this->unit->run($test, $expected_result, $test_name);
+
+
+

The expected result you supply can either be a literal match, or a data +type match. Here’s an example of a literal:

+
$this->unit->run('Foo', 'Foo');
+
+
+

Here is an example of a data type match:

+
$this->unit->run('Foo', 'is_string');
+
+
+

Notice the use of “is_string” in the second parameter? This tells the +function to evaluate whether your test is producing a string as the +result. Here is a list of allowed comparison types:

+
    +
  • is_object
  • +
  • is_string
  • +
  • is_bool
  • +
  • is_true
  • +
  • is_false
  • +
  • is_int
  • +
  • is_numeric
  • +
  • is_float
  • +
  • is_double
  • +
  • is_array
  • +
  • is_null
  • +
  • is_resource
  • +
+
+
+

Generating Reports

+

You can either display results after each test, or your can run several +tests and generate a report at the end. To show a report directly simply +echo or return the run function:

+
echo $this->unit->run($test, $expected_result);
+
+
+

To run a full report of all tests, use this:

+
echo $this->unit->report();
+
+
+

The report will be formatted in an HTML table for viewing. If you prefer +the raw data you can retrieve an array using:

+
echo $this->unit->result();
+
+
+
+
+

Strict Mode

+

By default the unit test class evaluates literal matches loosely. +Consider this example:

+
$this->unit->run(1, TRUE);
+
+
+

The test is evaluating an integer, but the expected result is a boolean. +PHP, however, due to it’s loose data-typing will evaluate the above code +as TRUE using a normal equality test:

+
if (1 == TRUE) echo 'This evaluates as true';
+
+
+

If you prefer, you can put the unit test class in to strict mode, which +will compare the data type as well as the value:

+
if (1 === TRUE) echo 'This evaluates as FALSE';
+
+
+

To enable strict mode use this:

+
$this->unit->use_strict(TRUE);
+
+
+
+
+

Enabling/Disabling Unit Testing

+

If you would like to leave some testing in place in your scripts, but +not have it run unless you need it, you can disable unit testing using:

+
$this->unit->active(FALSE);
+
+
+
+
+

Unit Test Display

+

When your unit test results display, the following items show by +default:

+
    +
  • Test Name (test_name)
  • +
  • Test Datatype (test_datatype)
  • +
  • Expected Datatype (res_datatype)
  • +
  • Result (result)
  • +
  • File Name (file)
  • +
  • Line Number (line)
  • +
  • Any notes you entered for the test (notes)
  • +
+

You can customize which of these items get displayed by using +$this->unit->set_test_items(). For example, if you only wanted the test name +and the result displayed:

+
+

Customizing displayed tests

+
$this->unit->set_test_items(array('test_name', 'result'));
+
+
+
+
+

Creating a Template

+

If you would like your test results formatted differently then the +default you can set your own template. Here is an example of a simple +template. Note the required pseudo-variables:

+
$str = '
+<table border="0" cellpadding="4" cellspacing="1">
+{rows}
+        <tr>
+                <td>{item}</td>
+                <td>{result}</td>
+        </tr>
+{/rows}
+</table>';
+
+$this->unit->set_template($str);
+
+
+
+

Note

+

Your template must be declared before running the unit +test process.

+
+
+
+
+
+

Class Reference

+
+
+class CI_Unit_test
+
+
+set_test_items($items)
+
+++ + + + + + +
Parameters:
    +
  • $items (array) – List of visible test items
  • +
+
Returns:

void

+
+

Sets a list of items that should be visible in tests. +Valid options are:

+
+
    +
  • test_name
  • +
  • test_datatype
  • +
  • res_datatype
  • +
  • result
  • +
  • file
  • +
  • line
  • +
  • notes
  • +
+
+
+ +
+
+run($test[, $expected = TRUE[, $test_name = 'undefined'[, $notes = '']]])
+
+++ + + + + + + + +
Parameters:
    +
  • $test (mixed) – Test data
  • +
  • $expected (mixed) – Expected result
  • +
  • $test_name (string) – Test name
  • +
  • $notes (string) – Any notes to be attached to the test
  • +
+
Returns:

Test report

+
Return type:

string

+
+

Runs unit tests.

+
+ +
+
+report([$result = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $result (array) – Array containing tests results
  • +
+
Returns:

Test report

+
Return type:

string

+
+

Generates a report about already complete tests.

+
+ +
+
+use_strict([$state = TRUE])
+
+++ + + + + + +
Parameters:
    +
  • $state (bool) – Strict state flag
  • +
+
Return type:

void

+
+

Enables/disables strict type comparison in tests.

+
+ +
+
+active([$state = TRUE])
+
+++ + + + + + +
Parameters:
    +
  • $state (bool) – Whether to enable testing
  • +
+
Return type:

void

+
+

Enables/disables unit testing.

+
+ +
+
+result([$results = array()])
+
+++ + + + + + + + +
Parameters:
    +
  • $results (array) – Tests results list
  • +
+
Returns:

Array of raw result data

+
Return type:

array

+
+

Returns raw tests results data.

+
+ +
+
+set_template($template)
+
+++ + + + + + +
Parameters:
    +
  • $template (string) – Test result template
  • +
+
Return type:

void

+
+

Sets the template for displaying tests results.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/uri.html b/user_guide/libraries/uri.html new file mode 100644 index 000000000..61d78ec77 --- /dev/null +++ b/user_guide/libraries/uri.html @@ -0,0 +1,890 @@ + + + + + + + + + + URI Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

URI Class

+

The URI Class provides methods that help you retrieve information from +your URI strings. If you use URI routing, you can also retrieve +information about the re-routed segments.

+
+

Note

+

This class is initialized automatically by the system so there +is no need to do it manually.

+
+ +
+

Class Reference

+
+
+class CI_URI
+
+
+segment($n[, $no_result = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $n (int) – Segment index number
  • +
  • $no_result (mixed) – What to return if the searched segment is not found
  • +
+
Returns:

Segment value or $no_result value if not found

+
Return type:

mixed

+
+

Permits you to retrieve a specific segment. Where n is the segment +number you wish to retrieve. Segments are numbered from left to right. +For example, if your full URL is this:

+
http://example.com/index.php/news/local/metro/crime_is_up
+
+
+

The segment numbers would be this:

+
    +
  1. news
  2. +
  3. local
  4. +
  5. metro
  6. +
  7. crime_is_up
  8. +
+

The optional second parameter defaults to NULL and allows you to set the return value +of this method when the requested URI segment is missing. +For example, this would tell the method to return the number zero in the event of failure:

+
$product_id = $this->uri->segment(3, 0);
+
+
+

It helps avoid having to write code like this:

+
if ($this->uri->segment(3) === FALSE)
+{
+        $product_id = 0;
+}
+else
+{
+        $product_id = $this->uri->segment(3);
+}
+
+
+
+ +
+
+rsegment($n[, $no_result = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $n (int) – Segment index number
  • +
  • $no_result (mixed) – What to return if the searched segment is not found
  • +
+
Returns:

Routed segment value or $no_result value if not found

+
Return type:

mixed

+
+

This method is identical to segment(), except that it lets you retrieve +a specific segment from your re-routed URI in the event you are +using CodeIgniter’s URI Routing feature.

+
+ +
+
+slash_segment($n[, $where = 'trailing'])
+
+++ + + + + + + + +
Parameters:
    +
  • $n (int) – Segment index number
  • +
  • $where (string) – Where to add the slash (‘trailing’ or ‘leading’)
  • +
+
Returns:

Segment value, prepended/suffixed with a forward slash, or a slash if not found

+
Return type:

string

+
+

This method is almost identical to segment(), except it +adds a trailing and/or leading slash based on the second parameter. +If the parameter is not used, a trailing slash added. Examples:

+
$this->uri->slash_segment(3);
+$this->uri->slash_segment(3, 'leading');
+$this->uri->slash_segment(3, 'both');
+
+
+

Returns:

+
    +
  1. segment/
  2. +
  3. /segment
  4. +
  5. /segment/
  6. +
+
+ +
+
+slash_rsegment($n[, $where = 'trailing'])
+
+++ + + + + + + + +
Parameters:
    +
  • $n (int) – Segment index number
  • +
  • $where (string) – Where to add the slash (‘trailing’ or ‘leading’)
  • +
+
Returns:

Routed segment value, prepended/suffixed with a forward slash, or a slash if not found

+
Return type:

string

+
+

This method is identical to slash_segment(), except that it lets you +add slashes a specific segment from your re-routed URI in the event you +are using CodeIgniter’s URI Routing +feature.

+
+ +
+
+uri_to_assoc([$n = 3[, $default = array()]])
+
+++ + + + + + + + +
Parameters:
    +
  • $n (int) – Segment index number
  • +
  • $default (array) – Default values
  • +
+
Returns:

Associative URI segments array

+
Return type:

array

+
+

This method lets you turn URI segments into an associative array of +key/value pairs. Consider this URI:

+
index.php/user/search/name/joe/location/UK/gender/male
+
+
+

Using this method you can turn the URI into an associative array with +this prototype:

+
[array]
+(
+        'name'          => 'joe'
+        'location'      => 'UK'
+        'gender'        => 'male'
+)
+
+
+

The first parameter lets you set an offset, which defaults to 3 since your +URI will normally contain a controller/method pair in the first and second segments. +Example:

+
$array = $this->uri->uri_to_assoc(3);
+echo $array['name'];
+
+
+

The second parameter lets you set default key names, so that the array +returned will always contain expected indexes, even if missing from the URI. +Example:

+
$default = array('name', 'gender', 'location', 'type', 'sort');
+$array = $this->uri->uri_to_assoc(3, $default);
+
+
+

If the URI does not contain a value in your default, an array index will +be set to that name, with a value of NULL.

+

Lastly, if a corresponding value is not found for a given key (if there +is an odd number of URI segments) the value will be set to NULL.

+
+ +
+
+ruri_to_assoc([$n = 3[, $default = array()]])
+
+++ + + + + + + + +
Parameters:
    +
  • $n (int) – Segment index number
  • +
  • $default (array) – Default values
  • +
+
Returns:

Associative routed URI segments array

+
Return type:

array

+
+

This method is identical to uri_to_assoc(), except that it creates +an associative array using the re-routed URI in the event you are using +CodeIgniter’s URI Routing feature.

+
+ +
+
+assoc_to_uri($array)
+
+++ + + + + + + + +
Parameters:
    +
  • $array (array) – Input array of key/value pairs
  • +
+
Returns:

URI string

+
Return type:

string

+
+

Takes an associative array as input and generates a URI string from it. +The array keys will be included in the string. Example:

+
$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
+$str = $this->uri->assoc_to_uri($array);
+
+// Produces: product/shoes/size/large/color/red
+
+
+
+ +
+
+uri_string()
+
+++ + + + + + +
Returns:URI string
Return type:string
+

Returns a string with the complete URI. For example, if this is your full URL:

+
http://example.com/index.php/news/local/345
+
+
+

The method would return this:

+
news/local/345
+
+
+
+ +
+
+ruri_string()
+
+++ + + + + + +
Returns:Routed URI string
Return type:string
+

This method is identical to uri_string(), except that it returns +the re-routed URI in the event you are using CodeIgniter’s URI +Routing feature.

+
+ +
+
+total_segments()
+
+++ + + + + + +
Returns:Count of URI segments
Return type:int
+

Returns the total number of segments.

+
+ +
+
+total_rsegments()
+
+++ + + + + + +
Returns:Count of routed URI segments
Return type:int
+

This method is identical to total_segments(), except that it returns +the total number of segments in your re-routed URI in the event you are +using CodeIgniter’s URI Routing feature.

+
+ +
+
+segment_array()
+
+++ + + + + + +
Returns:URI segments array
Return type:array
+

Returns an array containing the URI segments. For example:

+
$segs = $this->uri->segment_array();
+
+foreach ($segs as $segment)
+{
+        echo $segment;
+        echo '<br />';
+}
+
+
+
+ +
+
+rsegment_array()
+
+++ + + + + + +
Returns:Routed URI segments array
Return type:array
+

This method is identical to segment_array(), except that it returns +the array of segments in your re-routed URI in the event you are using +CodeIgniter’s URI Routing feature.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/user_agent.html b/user_guide/libraries/user_agent.html new file mode 100644 index 000000000..0f9e90067 --- /dev/null +++ b/user_guide/libraries/user_agent.html @@ -0,0 +1,931 @@ + + + + + + + + + + User Agent Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+ +
+
+
+ +
+

User Agent Class

+

The User Agent Class provides functions that help identify information +about the browser, mobile device, or robot visiting your site. In +addition you can get referrer information as well as language and +supported character-set information.

+ +
+

Using the User Agent Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the User Agent class is +initialized in your controller using the $this->load->library function:

+
$this->load->library('user_agent');
+
+
+

Once loaded, the object will be available using: $this->agent

+
+
+

User Agent Definitions

+

The user agent name definitions are located in a config file located at: +application/config/user_agents.php. You may add items to the various +user agent arrays if needed.

+
+
+

Example

+

When the User Agent class is initialized it will attempt to determine +whether the user agent browsing your site is a web browser, a mobile +device, or a robot. It will also gather the platform information if it +is available.

+
$this->load->library('user_agent');
+
+if ($this->agent->is_browser())
+{
+        $agent = $this->agent->browser().' '.$this->agent->version();
+}
+elseif ($this->agent->is_robot())
+{
+        $agent = $this->agent->robot();
+}
+elseif ($this->agent->is_mobile())
+{
+        $agent = $this->agent->mobile();
+}
+else
+{
+        $agent = 'Unidentified User Agent';
+}
+
+echo $agent;
+
+echo $this->agent->platform(); // Platform info (Windows, Linux, Mac, etc.)
+
+
+
+
+
+

Class Reference

+
+
+class CI_User_agent
+
+
+is_browser([$key = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Optional browser name
  • +
+
Returns:

TRUE if the user agent is a (specified) browser, FALSE if not

+
Return type:

bool

+
+

Returns TRUE/FALSE (boolean) if the user agent is a known web browser.

+
if ($this->agent->is_browser('Safari'))
+{
+        echo 'You are using Safari.';
+}
+elseif ($this->agent->is_browser())
+{
+        echo 'You are using a browser.';
+}
+
+
+
+

Note

+

The string “Safari” in this example is an array key in the list of browser definitions. +You can find this list in application/config/user_agents.php if you want to add new +browsers or change the stings.

+
+
+ +
+
+is_mobile([$key = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Optional mobile device name
  • +
+
Returns:

TRUE if the user agent is a (specified) mobile device, FALSE if not

+
Return type:

bool

+
+

Returns TRUE/FALSE (boolean) if the user agent is a known mobile device.

+
if ($this->agent->is_mobile('iphone'))
+{
+        $this->load->view('iphone/home');
+}
+elseif ($this->agent->is_mobile())
+{
+        $this->load->view('mobile/home');
+}
+else
+{
+        $this->load->view('web/home');
+}
+
+
+
+ +
+
+is_robot([$key = NULL])
+
+++ + + + + + + + +
Parameters:
    +
  • $key (string) – Optional robot name
  • +
+
Returns:

TRUE if the user agent is a (specified) robot, FALSE if not

+
Return type:

bool

+
+

Returns TRUE/FALSE (boolean) if the user agent is a known robot.

+
+

Note

+

The user agent library only contains the most common robot definitions. It is not a complete list of bots. +There are hundreds of them so searching for each one would not be very efficient. If you find that some bots +that commonly visit your site are missing from the list you can add them to your +application/config/user_agents.php file.

+
+
+ +
+
+is_referral()
+
+++ + + + + + +
Returns:TRUE if the user agent is a referral, FALSE if not
Return type:bool
+

Returns TRUE/FALSE (boolean) if the user agent was referred from another site.

+
+ +
+
+browser()
+
+++ + + + + + +
Returns:Detected browser or an empty string
Return type:string
+

Returns a string containing the name of the web browser viewing your site.

+
+ +
+
+version()
+
+++ + + + + + +
Returns:Detected browser version or an empty string
Return type:string
+

Returns a string containing the version number of the web browser viewing your site.

+
+ +
+
+mobile()
+
+++ + + + + + +
Returns:Detected mobile device brand or an empty string
Return type:string
+

Returns a string containing the name of the mobile device viewing your site.

+
+ +
+
+robot()
+
+++ + + + + + +
Returns:Detected robot name or an empty string
Return type:string
+

Returns a string containing the name of the robot viewing your site.

+
+ +
+
+platform()
+
+++ + + + + + +
Returns:Detected operating system or an empty string
Return type:string
+

Returns a string containing the platform viewing your site (Linux, Windows, OS X, etc.).

+
+ +
+
+referrer()
+
+++ + + + + + +
Returns:Detected referrer or an empty string
Return type:string
+

The referrer, if the user agent was referred from another site. Typically you’ll test for this as follows:

+
if ($this->agent->is_referral())
+{
+        echo $this->agent->referrer();
+}
+
+
+
+ +
+
+agent_string()
+
+++ + + + + + +
Returns:Full user agent string or an empty string
Return type:string
+

Returns a string containing the full user agent string. Typically it will be something like this:

+
Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.4) Gecko/20060613 Camino/1.0.2
+
+
+
+ +
+
+accept_lang([$lang = 'en'])
+
+++ + + + + + + + +
Parameters:
    +
  • $lang (string) – Language key
  • +
+
Returns:

TRUE if provided language is accepted, FALSE if not

+
Return type:

bool

+
+

Lets you determine if the user agent accepts a particular language. Example:

+
if ($this->agent->accept_lang('en'))
+{
+        echo 'You accept English!';
+}
+
+
+
+

Note

+

This method is not typically very reliable since some browsers do not provide language info, +and even among those that do, it is not always accurate.

+
+
+ +
+
+languages()
+
+++ + + + + + +
Returns:An array list of accepted languages
Return type:array
+

Returns an array of languages supported by the user agent.

+
+ +
+
+accept_charset([$charset = 'utf-8'])
+
+++ + + + + + + + +
Parameters:
    +
  • $charset (string) – Character set
  • +
+
Returns:

TRUE if the character set is accepted, FALSE if not

+
Return type:

bool

+
+

Lets you determine if the user agent accepts a particular character set. Example:

+
if ($this->agent->accept_charset('utf-8'))
+{
+        echo 'You browser supports UTF-8!';
+}
+
+
+
+

Note

+

This method is not typically very reliable since some browsers do not provide character-set info, +and even among those that do, it is not always accurate.

+
+
+ +
+
+charsets()
+
+++ + + + + + +
Returns:An array list of accepted character sets
Return type:array
+

Returns an array of character sets accepted by the user agent.

+
+ +
+
+parse($string)
+
+++ + + + + + +
Parameters:
    +
  • $string (string) – A custom user-agent string
  • +
+
Return type:

void

+
+

Parses a custom user-agent string, different from the one reported by the current visitor.

+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/xmlrpc.html b/user_guide/libraries/xmlrpc.html new file mode 100644 index 000000000..8f1f1b008 --- /dev/null +++ b/user_guide/libraries/xmlrpc.html @@ -0,0 +1,1151 @@ + + + + + + + + + + XML-RPC and XML-RPC Server Classes — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • XML-RPC and XML-RPC Server Classes
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

XML-RPC and XML-RPC Server Classes

+

CodeIgniter’s XML-RPC classes permit you to send requests to another +server, or set up your own XML-RPC server to receive requests.

+ +
+

What is XML-RPC?

+

Quite simply it is a way for two computers to communicate over the +internet using XML. One computer, which we will call the client, sends +an XML-RPC request to another computer, which we will call the +server. Once the server receives and processes the request it will send +back a response to the client.

+

For example, using the MetaWeblog API, an XML-RPC Client (usually a +desktop publishing tool) will send a request to an XML-RPC Server +running on your site. This request might be a new weblog entry being +sent for publication, or it could be a request for an existing entry for +editing. When the XML-RPC Server receives this request it will examine +it to determine which class/method should be called to process the +request. Once processed, the server will then send back a response +message.

+

For detailed specifications, you can visit the XML-RPC site.

+
+
+

Using the XML-RPC Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the XML-RPC and XML-RPCS classes +are initialized in your controller using the $this->load->library +function:

+

To load the XML-RPC class you will use:

+
$this->load->library('xmlrpc');
+
+
+

Once loaded, the xml-rpc library object will be available using: +$this->xmlrpc

+

To load the XML-RPC Server class you will use:

+
$this->load->library('xmlrpc');
+$this->load->library('xmlrpcs');
+
+
+

Once loaded, the xml-rpcs library object will be available using: +$this->xmlrpcs

+
+

Note

+

When using the XML-RPC Server class you must load BOTH the +XML-RPC class and the XML-RPC Server class.

+
+
+
+

Sending XML-RPC Requests

+

To send a request to an XML-RPC server you must specify the following +information:

+
    +
  • The URL of the server
  • +
  • The method on the server you wish to call
  • +
  • The request data (explained below).
  • +
+

Here is a basic example that sends a simple Weblogs.com ping to the +Ping-o-Matic

+
$this->load->library('xmlrpc');
+
+$this->xmlrpc->server('http://rpc.pingomatic.com/', 80);
+$this->xmlrpc->method('weblogUpdates.ping');
+
+$request = array('My Photoblog', 'http://www.my-site.com/photoblog/');
+$this->xmlrpc->request($request);
+
+if ( ! $this->xmlrpc->send_request())
+{
+        echo $this->xmlrpc->display_error();
+}
+
+
+
+

Explanation

+

The above code initializes the XML-RPC class, sets the server URL and +method to be called (weblogUpdates.ping). The request (in this case, the +title and URL of your site) is placed into an array for transportation, +and compiled using the request() function. Lastly, the full request is +sent. If the send_request() method returns false we will display the +error message sent back from the XML-RPC Server.

+
+
+
+

Anatomy of a Request

+

An XML-RPC request is simply the data you are sending to the XML-RPC +server. Each piece of data in a request is referred to as a request +parameter. The above example has two parameters: The URL and title of +your site. When the XML-RPC server receives your request, it will look +for parameters it requires.

+

Request parameters must be placed into an array for transportation, and +each parameter can be one of seven data types (strings, numbers, dates, +etc.). If your parameters are something other than strings you will have +to include the data type in the request array.

+

Here is an example of a simple array with three parameters:

+
$request = array('John', 'Doe', 'www.some-site.com');
+$this->xmlrpc->request($request);
+
+
+

If you use data types other than strings, or if you have several +different data types, you will place each parameter into its own array, +with the data type in the second position:

+
$request = array(
+        array('John', 'string'),
+        array('Doe', 'string'),
+        array(FALSE, 'boolean'),
+        array(12345, 'int')
+);
+$this->xmlrpc->request($request);
+
+
+

The Data Types section below has a full list of data +types.

+
+
+

Creating an XML-RPC Server

+

An XML-RPC Server acts as a traffic cop of sorts, waiting for incoming +requests and redirecting them to the appropriate functions for +processing.

+

To create your own XML-RPC server involves initializing the XML-RPC +Server class in your controller where you expect the incoming request to +appear, then setting up an array with mapping instructions so that +incoming requests can be sent to the appropriate class and method for +processing.

+

Here is an example to illustrate:

+
$this->load->library('xmlrpc');
+$this->load->library('xmlrpcs');
+
+$config['functions']['new_post'] = array('function' => 'My_blog.new_entry');
+$config['functions']['update_post'] = array('function' => 'My_blog.update_entry');
+$config['object'] = $this;
+
+$this->xmlrpcs->initialize($config);
+$this->xmlrpcs->serve();
+
+
+

The above example contains an array specifying two method requests that +the Server allows. The allowed methods are on the left side of the +array. When either of those are received, they will be mapped to the +class and method on the right.

+

The ‘object’ key is a special key that you pass an instantiated class +object with, which is necessary when the method you are mapping to is +not part of the CodeIgniter super object.

+

In other words, if an XML-RPC Client sends a request for the new_post +method, your server will load the My_blog class and call the new_entry +function. If the request is for the update_post method, your server +will load the My_blog class and call the update_entry() method.

+

The function names in the above example are arbitrary. You’ll decide +what they should be called on your server, or if you are using +standardized APIs, like the Blogger or MetaWeblog API, you’ll use their +function names.

+

There are two additional configuration keys you may make use of when +initializing the server class: debug can be set to TRUE in order to +enable debugging, and xss_clean may be set to FALSE to prevent sending +data through the Security library’s xss_clean() method.

+
+
+

Processing Server Requests

+

When the XML-RPC Server receives a request and loads the class/method +for processing, it will pass an object to that method containing the +data sent by the client.

+

Using the above example, if the new_post method is requested, the +server will expect a class to exist with this prototype:

+
class My_blog extends CI_Controller {
+
+        public function new_post($request)
+        {
+
+        }
+}
+
+
+

The $request variable is an object compiled by the Server, which +contains the data sent by the XML-RPC Client. Using this object you will +have access to the request parameters enabling you to process the +request. When you are done you will send a Response back to the Client.

+

Below is a real-world example, using the Blogger API. One of the methods +in the Blogger API is getUserInfo(). Using this method, an XML-RPC +Client can send the Server a username and password, in return the Server +sends back information about that particular user (nickname, user ID, +email address, etc.). Here is how the processing function might look:

+
class My_blog extends CI_Controller {
+
+        public function getUserInfo($request)
+        {
+                $username = 'smitty';
+                $password = 'secretsmittypass';
+
+                $this->load->library('xmlrpc');
+
+                $parameters = $request->output_parameters();
+
+                if ($parameters[1] != $username && $parameters[2] != $password)
+                {
+                        return $this->xmlrpc->send_error_message('100', 'Invalid Access');
+                }
+
+                $response = array(
+                        array(
+                                'nickname'  => array('Smitty', 'string'),
+                                'userid'    => array('99', 'string'),
+                                'url'       => array('http://yoursite.com', 'string'),
+                                'email'     => array('jsmith@yoursite.com', 'string'),
+                                'lastname'  => array('Smith', 'string'),
+                                'firstname' => array('John', 'string')
+                        ),
+                         'struct'
+                );
+
+                return $this->xmlrpc->send_response($response);
+        }
+}
+
+
+
+

Notes:

+

The output_parameters() method retrieves an indexed array +corresponding to the request parameters sent by the client. In the above +example, the output parameters will be the username and password.

+

If the username and password sent by the client were not valid, and +error message is returned using send_error_message().

+

If the operation was successful, the client will be sent back a response +array containing the user’s info.

+
+
+
+

Formatting a Response

+

Similar to Requests, Responses must be formatted as an array. +However, unlike requests, a response is an array that contains a +single item. This item can be an array with several additional arrays, +but there can be only one primary array index. In other words, the basic +prototype is this:

+
$response = array('Response data', 'array');
+
+
+

Responses, however, usually contain multiple pieces of information. In +order to accomplish this we must put the response into its own array so +that the primary array continues to contain a single piece of data. +Here’s an example showing how this might be accomplished:

+
$response = array(
+        array(
+                'first_name' => array('John', 'string'),
+                'last_name' => array('Doe', 'string'),
+                'member_id' => array(123435, 'int'),
+                'todo_list' => array(array('clean house', 'call mom', 'water plants'), 'array'),
+        ),
+        'struct'
+);
+
+
+

Notice that the above array is formatted as a struct. This is the most +common data type for responses.

+

As with Requests, a response can be one of the seven data types listed +in the Data Types section.

+
+
+

Sending an Error Response

+

If you need to send the client an error response you will use the +following:

+
return $this->xmlrpc->send_error_message('123', 'Requested data not available');
+
+
+

The first parameter is the error number while the second parameter is +the error message.

+
+
+

Creating Your Own Client and Server

+

To help you understand everything we’ve covered thus far, let’s create a +couple controllers that act as XML-RPC Client and Server. You’ll use the +Client to send a request to the Server and receive a response.

+
+

The Client

+

Using a text editor, create a controller called Xmlrpc_client.php. In +it, place this code and save it to your application/controllers/ +folder:

+
<?php
+
+class Xmlrpc_client extends CI_Controller {
+
+        public function index()
+        {
+                $this->load->helper('url');
+                $server_url = site_url('xmlrpc_server');
+
+                $this->load->library('xmlrpc');
+
+                $this->xmlrpc->server($server_url, 80);
+                $this->xmlrpc->method('Greetings');
+
+                $request = array('How is it going?');
+                $this->xmlrpc->request($request);
+
+                if ( ! $this->xmlrpc->send_request())
+                {
+                        echo $this->xmlrpc->display_error();
+                }
+                else
+                {
+                        echo '<pre>';
+                        print_r($this->xmlrpc->display_response());
+                        echo '</pre>';
+                }
+        }
+}
+?>
+
+
+
+

Note

+

In the above code we are using a “url helper”. You can find more +information in the Helpers Functions page.

+
+
+
+

The Server

+

Using a text editor, create a controller called Xmlrpc_server.php. In +it, place this code and save it to your application/controllers/ +folder:

+
<?php
+
+class Xmlrpc_server extends CI_Controller {
+
+        public function index()
+        {
+                $this->load->library('xmlrpc');
+                $this->load->library('xmlrpcs');
+
+                $config['functions']['Greetings'] = array('function' => 'Xmlrpc_server.process');
+
+                $this->xmlrpcs->initialize($config);
+                $this->xmlrpcs->serve();
+        }
+
+
+        public function process($request)
+        {
+                $parameters = $request->output_parameters();
+
+                $response = array(
+                        array(
+                                'you_said'  => $parameters[0],
+                                'i_respond' => 'Not bad at all.'
+                        ),
+                        'struct'
+                );
+
+                return $this->xmlrpc->send_response($response);
+        }
+}
+
+
+
+
+

Try it!

+

Now visit the your site using a URL similar to this:

+
example.com/index.php/xmlrpc_client/
+
+
+

You should now see the message you sent to the server, and its response +back to you.

+

The client you created sends a message (“How’s is going?”) to the +server, along with a request for the “Greetings” method. The Server +receives the request and maps it to the process() method, where a +response is sent back.

+
+
+
+

Using Associative Arrays In a Request Parameter

+

If you wish to use an associative array in your method parameters you +will need to use a struct datatype:

+
$request = array(
+        array(
+                // Param 0
+                array('name' => 'John'),
+                'struct'
+        ),
+        array(
+                // Param 1
+                array(
+                        'size' => 'large',
+                        'shape'=>'round'
+                ),
+                'struct'
+        )
+);
+
+$this->xmlrpc->request($request);
+
+
+

You can retrieve the associative array when processing the request in +the Server.

+
$parameters = $request->output_parameters();
+$name = $parameters[0]['name'];
+$size = $parameters[1]['size'];
+$shape = $parameters[1]['shape'];
+
+
+
+
+

Data Types

+

According to the XML-RPC spec there are +seven types of values that you can send via XML-RPC:

+
    +
  • int or i4
  • +
  • boolean
  • +
  • string
  • +
  • double
  • +
  • dateTime.iso8601
  • +
  • base64
  • +
  • struct (contains array of values)
  • +
  • array (contains array of values)
  • +
+
+
+
+

Class Reference

+
+
+class CI_Xmlrpc
+
+
+initialize([$config = array()])
+
+++ + + + + + +
Parameters:
    +
  • $config (array) – Configuration data
  • +
+
Return type:

void

+
+

Initializes the XML-RPC library. Accepts an associative array containing your settings.

+
+ +
+
+server($url[, $port = 80[, $proxy = FALSE[, $proxy_port = 8080]]])
+
+++ + + + + + +
Parameters:
    +
  • $url (string) – XML-RPC server URL
  • +
  • $port (int) – Server port
  • +
  • $proxy (string) – Optional proxy
  • +
  • $proxy_port (int) – Proxy listening port
  • +
+
Return type:

void

+
+

Sets the URL and port number of the server to which a request is to be sent:

+
$this->xmlrpc->server('http://www.sometimes.com/pings.php', 80);
+
+
+

Basic HTTP authentication is also supported, simply add it to the server URL:

+
$this->xmlrpc->server('http://user:pass@localhost/', 80);
+
+
+
+ +
+
+timeout($seconds = 5)
+
+++ + + + + + +
Parameters:
    +
  • $seconds (int) – Timeout in seconds
  • +
+
Return type:

void

+
+

Set a time out period (in seconds) after which the request will be canceled:

+
$this->xmlrpc->timeout(6);
+
+
+

This timeout period will be used both for an initial connection to +the remote server, as well as for getting a response from it. +Make sure you set the timeout before calling send_request().

+
+ +
+
+method($function)
+
+++ + + + + + +
Parameters:
    +
  • $function (string) – Method name
  • +
+
Return type:

void

+
+

Sets the method that will be requested from the XML-RPC server:

+
$this->xmlrpc->method('method');
+
+
+

Where method is the name of the method.

+
+ +
+
+request($incoming)
+
+++ + + + + + +
Parameters:
    +
  • $incoming (array) – Request data
  • +
+
Return type:

void

+
+

Takes an array of data and builds request to be sent to XML-RPC server:

+
$request = array(array('My Photoblog', 'string'), 'http://www.yoursite.com/photoblog/');
+$this->xmlrpc->request($request);
+
+
+
+ +
+
+send_request()
+
+++ + + + + + +
Returns:TRUE on success, FALSE on failure
Return type:bool
+

The request sending method. Returns boolean TRUE or FALSE based on success for failure, enabling it to be used conditionally.

+
+ +
+
+display_error()
+
+++ + + + + + +
Returns:Error message string
Return type:string
+

Returns an error message as a string if your request failed for some reason.

+
echo $this->xmlrpc->display_error();
+
+
+
+ +
+
+display_response()
+
+++ + + + + + +
Returns:Response
Return type:mixed
+

Returns the response from the remote server once request is received. The response will typically be an associative array.

+
$this->xmlrpc->display_response();
+
+
+
+ +
+
+send_error_message($number, $message)
+
+++ + + + + + + + +
Parameters:
    +
  • $number (int) – Error number
  • +
  • $message (string) – Error message
  • +
+
Returns:

XML_RPC_Response instance

+
Return type:

XML_RPC_Response

+
+

This method lets you send an error message from your server to the client. +First parameter is the error number while the second parameter is the error message.

+
return $this->xmlrpc->send_error_message(123, 'Requested data not available');
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/user_guide/libraries/zip.html b/user_guide/libraries/zip.html new file mode 100644 index 000000000..2e4f9f80c --- /dev/null +++ b/user_guide/libraries/zip.html @@ -0,0 +1,846 @@ + + + + + + + + + + Zip Encoding Class — CodeIgniter 3.1.7 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + + + + +
+
+
+
    +
  • Docs »
  • + +
  • Libraries »
  • + +
  • Zip Encoding Class
  • +
  • + +
  • +
    + classic layout +
    +
+
+
+
+ +
+

Zip Encoding Class

+

CodeIgniter’s Zip Encoding Class permits you to create Zip archives. +Archives can be downloaded to your desktop or saved to a directory.

+ +
+

Using the Zip Encoding Class

+
+

Initializing the Class

+

Like most other classes in CodeIgniter, the Zip class is initialized in +your controller using the $this->load->library function:

+
$this->load->library('zip');
+
+
+

Once loaded, the Zip library object will be available using:

+
$this->zip
+
+
+
+
+

Usage Example

+

This example demonstrates how to compress a file, save it to a folder on +your server, and download it to your desktop.

+
$name = 'mydata1.txt';
+$data = 'A Data String!';
+
+$this->zip->add_data($name, $data);
+
+// Write the zip file to a folder on your server. Name it "my_backup.zip"
+$this->zip->archive('/path/to/directory/my_backup.zip');
+
+// Download the file to your desktop. Name it "my_backup.zip"
+$this->zip->download('my_backup.zip');
+
+
+
+
+
+

Class Reference

+
+
+class CI_Zip
+
+
+$compression_level = 2
+

The compression level to use.

+

It can range from 0 to 9, with 9 being the highest and 0 effectively disabling compression:

+
$this->zip->compression_level = 0;
+
+
+
+ +
+
+add_data($filepath[, $data = NULL])
+
+++ + + + + + +
Parameters:
    +
  • $filepath (mixed) – A single file path or an array of file => data pairs
  • +
  • $data (array) – File contents (ignored if $filepath is an array)
  • +
+
Return type:

void

+
+

Adds data to the Zip archive. Can work both in single and multiple files mode.

+

When adding a single file, the first parameter must contain the name you would +like given to the file and the second must contain the file contents:

+
$name = 'mydata1.txt';
+$data = 'A Data String!';
+$this->zip->add_data($name, $data);
+
+$name = 'mydata2.txt';
+$data = 'Another Data String!';
+$this->zip->add_data($name, $data);
+
+
+

When adding multiple files, the first parameter must contain file => contents pairs +and the second parameter is ignored:

+
$data = array(
+        'mydata1.txt' => 'A Data String!',
+        'mydata2.txt' => 'Another Data String!'
+);
+
+$this->zip->add_data($data);
+
+
+

If you would like your compressed data organized into sub-directories, simply include +the path as part of the filename(s):

+
$name = 'personal/my_bio.txt';
+$data = 'I was born in an elevator...';
+
+$this->zip->add_data($name, $data);
+
+
+

The above example will place my_bio.txt inside a folder called personal.

+
+ +
+
+add_dir($directory)
+
+++ + + + + + +
Parameters:
    +
  • $directory (mixed) – Directory name string or an array of multiple directories
  • +
+
Return type:

void

+
+

Permits you to add a directory. Usually this method is unnecessary since you can place +your data into directories when using $this->zip->add_data(), but if you would like +to create an empty directory you can do so:

+
$this->zip->add_dir('myfolder'); // Creates a directory called "myfolder"
+
+
+
+ +
+
+read_file($path[, $archive_filepath = FALSE])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Path to file
  • +
  • $archive_filepath (mixed) – New file name/path (string) or (boolean) whether to maintain the original filepath
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Permits you to compress a file that already exists somewhere on your server. +Supply a file path and the zip class will read it and add it to the archive:

+
$path = '/path/to/photo.jpg';
+
+$this->zip->read_file($path);
+
+// Download the file to your desktop. Name it "my_backup.zip"
+$this->zip->download('my_backup.zip');
+
+
+

If you would like the Zip archive to maintain the directory structure of +the file in it, pass TRUE (boolean) in the second parameter. Example:

+
$path = '/path/to/photo.jpg';
+
+$this->zip->read_file($path, TRUE);
+
+// Download the file to your desktop. Name it "my_backup.zip"
+$this->zip->download('my_backup.zip');
+
+
+

In the above example, photo.jpg will be placed into the path/to/ directory.

+

You can also specify a new name (path included) for the added file on the fly:

+
$path = '/path/to/photo.jpg';
+$new_path = '/new/path/some_photo.jpg';
+
+$this->zip->read_file($path, $new_path);
+
+// Download ZIP archive containing /new/path/some_photo.jpg
+$this->zip->download('my_archive.zip');
+
+
+
+ +
+
+read_dir($path[, $preserve_filepath = TRUE[, $root_path = NULL]])
+
+++ + + + + + + + +
Parameters:
    +
  • $path (string) – Path to directory
  • +
  • $preserve_filepath (bool) – Whether to maintain the original path
  • +
  • $root_path (string) – Part of the path to exclude from the archive directory
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Permits you to compress a directory (and its contents) that already exists somewhere on your server. +Supply a path to the directory and the zip class will recursively read and recreate it as a Zip archive. +All files contained within the supplied path will be encoded, as will any sub-directories contained within it. Example:

+
$path = '/path/to/your/directory/';
+
+$this->zip->read_dir($path);
+
+// Download the file to your desktop. Name it "my_backup.zip"
+$this->zip->download('my_backup.zip');
+
+
+

By default the Zip archive will place all directories listed in the first parameter +inside the zip. If you want the tree preceding the target directory to be ignored, +you can pass FALSE (boolean) in the second parameter. Example:

+
$path = '/path/to/your/directory/';
+
+$this->zip->read_dir($path, FALSE);
+
+
+

This will create a ZIP with a directory named “directory” inside, then all sub-directories +stored correctly inside that, but will not include the /path/to/your part of the path.

+
+ +
+
+archive($filepath)
+
+++ + + + + + + + +
Parameters:
    +
  • $filepath (string) – Path to target zip archive
  • +
+
Returns:

TRUE on success, FALSE on failure

+
Return type:

bool

+
+

Writes the Zip-encoded file to a directory on your server. Submit a valid server path +ending in the file name. Make sure the directory is writable (755 is usually OK). +Example:

+
$this->zip->archive('/path/to/folder/myarchive.zip'); // Creates a file named myarchive.zip
+
+
+
+ +
+
+download($filename = 'backup.zip')
+
+++ + + + + + +
Parameters:
    +
  • $filename (string) – Archive file name
  • +
+
Return type:

void

+
+

Causes the Zip file to be downloaded from your server. +You must pass the name you would like the zip file called. Example:

+
$this->zip->download('latest_stuff.zip'); // File will be named "latest_stuff.zip"
+
+
+
+

Note

+

Do not display any data in the controller in which you call +this method since it sends various server headers that cause the +download to happen and the file to be treated as binary.

+
+
+ +
+
+get_zip()
+
+++ + + + + + +
Returns:Zip file content
Return type:string
+

Returns the Zip-compressed file data. Generally you will not need this method unless you +want to do something unique with the data. Example:

+
$name = 'my_bio.txt';
+$data = 'I was born in an elevator...';
+
+$this->zip->add_data($name, $data);
+
+$zip_file = $this->zip->get_zip();
+
+
+
+ +
+
+clear_data()
+
+++ + + + +
Return type:void
+

The Zip class caches your zip data so that it doesn’t need to recompile the Zip archive +for each method you use above. If, however, you need to create multiple Zip archives, +each with different data, you can clear the cache between calls. Example:

+
$name = 'my_bio.txt';
+$data = 'I was born in an elevator...';
+
+$this->zip->add_data($name, $data);
+$zip_file = $this->zip->get_zip();
+
+$this->zip->clear_data();
+
+$name = 'photo.jpg';
+$this->zip->read_file("/path/to/photo.jpg"); // Read the file's contents
+
+$this->zip->download('myphotos.zip');
+
+
+
+ +
+ +
+
+ + +
+
+ + + + +
+ +
+

+ © Copyright 2014 - 2018, British Columbia Institute of Technology. + Last updated on Jan 13, 2018. +

+
+ + Built with Sphinx using a theme provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- cgit v1.2.3-24-g4f1b