Category Archives: Codeigniter Tutorial
Codeigniter Session Class Library
Codeigniter Session Class Library -We can load session class library like this $this->load->library(‘session’);. This library provide various functions that are used to maintain a user’s “state” and track thier activity while they browse your site. It has some session storage driver like file, database, redis, memcached. Here in this tutorial, we are going to explain how to use session class library.
Codeigniter session class library | Example
Let us understand how session class library works in codeigniter with examples.
Load session class library
First load session class library to use its functions, this library can be loaded simply as below-
How to load session class library:
$this->load->library('session'); |
Functions:-
There are following functions available in session class library. Now we will explain one by one.
- 1. Retrieving or add Session Data.
- 2. Removing Session Data.
- 3. Flashdata.
- 4. Tempdata.
- 5. Destroying a Session.
- 6. Accessing session metadata.
1. Retrieving or add Session Data.
Here is simple demo of retrieving or add session data.
Controller Code:-
Syntax of retrieving or add session data.
load->library('session'); $this->session->set_userdata('name','Welcome To Tutorialsplane'); $this->load->view('session_view'); } } ?> |
View Code:-
Syntax of retrieving session data on view page.
session->userdata('name'); ?> |
Output will be look like this
2. Removing Session Data.
Here is simple demo of Removing Session Data.
Controller Code:-
Syntax of Removing Session Data.
load->library('session'); $this->session->unset_userdata('name'); $this->load->view('library/session_view'); } } ?> |
View Code:-
Syntax of Removing Session Data on view page.
session->userdata('name'); ?> |
After click the unset button data will be automatically unset.
Output will be look like this
3. Flashdata.
Here is simple demo of Flashdata.
Controller Code:-
Syntax of Flashdata.
load->library('session'); $this->load->helper('url'); $this->session->set_flashdata('item','Welcome to solid coupon'); echo $this->session->flashdata('item'); } } ?> |
Output will be look like this
4. Tempdata.
Here is simple demo of tempdata.
Controller Code:-
Syntax of tempdata example.
load->library('session'); $this->load->helper('url'); $this->session->set_tempdata('Company name','SolidCoupon', 240); echo $this->session->tempdata('Company name'); } } ?> |
Output will be look like this
5. Destroying a Session.
Here is simple demo of destroying a session.
Controller Code:-
Syntax of destroying a session.
session->sess_destroy(); redirect(base_url()); } } ?> |
Output will be look like this
6. Accessing session metadata.
This session library comes with four session driver.
- Files Driver.
- Database Driver.
- Redis Driver.
- Memcached Driver.
- Parameters :
- $key (mixed) : Session item key or NULL
- Returns : Value of the specified item key, or an array of all userdata
- Returns type : Mixed
- Parameters :
- Returns : An array of all userdata
- Returns type : Array
- Parameters :
- Returns : A reference to $_SESSION
- Returns type : Array
- Parameters :
- $key (string) : Session item key
- Returns : TRUE if the specified key exists, FALSE if not
- Returns type : Bool
- 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
- Returns type : Void
- Parameters :
- $key (mixed) : Key for the session data item to unset, or an array of multiple keys.
- Returns type : Void
- Parameters :
- $key (mixed) : Key to mark as flashdata, or an array of multiple keys.
- Returns : TRUE on success, FALSE on failure
- Returns type : Bool
- Parameters :
- Returns : Array containing the keys of all “flashdata” items
- Returns type : Array
- Parameters :
- Returns : Array containing the keys of all “flashdata” items
- Returns type : Array
- Parameters :
- $key (mixed) : Flashdata item key or NULL
- Returns : Value of the specified item key, or an array of all flashdata
- Returns type : Mixed
- Parameters :
- $key (mixed) : Flashdata key to keep, or an array of multiple keys
- Returns : TRUE on success, FALSE on failure.
- Returns type : Bool
- 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
- Returns type : void
- 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
- Returns type : Bool
- Parameters :
- Returns : Array containing the keys of all “tempdata” items.
- Returns type : Array
- Parameters :
- $key (mixed) : Key to be un-marked as tempdata, or an array of multiple keys
- Returns type : Void
- Parameters :
- $key (mixed) : Tempdata item key or NULL
- Returns : Value of the specified item key, or an array of all tempdata
- Returns type : Mixed
- 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
- Returns type : Void
- Parameters :
- $destroy (bool) : Whether to destroy session data
- Returns type : Void
- Parameters :
- Returns type : Void
- Parameters :
- $key (string) : Session item key
- Returns : The requested session data item, or NULL if it doesn’t exist
- Returns type : Mixed
- Parameters :
- $key (string) : Session item key
- $value (mixed) : Value to assign to the session item key
- Returns type : Void
Files Driver.
This file driver use your file system for storing session data.
You should do something like this:-
mkdir /path to directory/sessions/ chmod 0700 /path to directory/sessions/ chown www-data /path to directory/sessions/ |
Database Driver.
The database driver use a relational database such as MYSQL and PostgreSQL to store session.
You should do something like this:-
$config['sess_driver'] = 'database'; $config['sess_save_path'] = 'ci_sessions'; |
Redis Driver.
Redis driver is a storage engine which is used for caching and popular because for high performance.
You should do something like this:-
$config['sess_driver'] = 'redis'; $config['sess_save_path'] = 'tcp://localhost:6379'; |
Memcached Driver.
This driver is similar to ‘redis’ one in all of its properties, except perhaps for availability.
You should do something like this:-
$config['sess_driver'] = 'memcached'; $config['sess_save_path'] = 'localhost:11211'; |
Class reference:-
There are following references available in session class library. Now we will explain.
1. Userdata.
This reference is used to get a value for a specific session item.
userdata([$key = NULL])
2. All userdata.
This function return an array containing all userdata item.
all_userdata()
3. Get userdata.
This function return a reference to the $_session array .
&get_userdata()
4. Has userdata.
This function check if an item exits in $_session.
has_userdata($key)
5. Set userdata.
This method is used to assign data to the $_session super global.
set_userdata($data[$value = NULL])
6. Unset userdata.
This method is used to unset the key from the $_session super global.
unset_userdata($key)
7. Mark as flash.
This method is used for mark a $_session item key(multiple key) as flashdata.
mark_as_flash($key)
8. Get flash keys.
This function get a list of all $_session which is marked as flashdata.
get_flash_keys()
9. Unmark flash.
This function unmark a $_session item key(Multiple one) as flashdata.
get_flash_keys()
10. Flashdata.
This method is used to get a specific $_session item that has been marked as flashdata.
flashdata([$key = NULL])
11. Keep flashdata.
This method is used to get a specific session data key as flashdata through next request.
keep_flashdata($key)
12. Set flashdata.
This method is used to assign data to the $_SESSION superglobal and marked as flashdata.
set_flashdata($data[$value = NULL])
13. Mark as temp.
This function is used to marked a session item key(Multiple one) as tempdata.
mark_as_temp($key[$ttl = 300])
14. Get temp keys.
This function get a list of all $_session which is marked as tempdata.
get_temp_keys()
15. Unmark temp.
This function unmarks a $_SESSION item key (multiple one) as tempdata.
unmark_temp($key)
16. Tempdata.
This function is used to get the value for a specific $_SESSION item which is marked as tempdata.
tempdata([$key = NULL])
17. Set tempdata.
This function is used to assign data to $_session superglobal and marked as tempdata .
set_tempdata($data[$value = NULL])
18. Sess regenerate.
This is used to regenerate session ID and optionally destroying the current session data.
sess_regenerate([$destroy = FALSE])
19. Sess destroy.
This function is used to destroy the current session.
sess_destroy()
20. Get.
This is a magic function that allows to return the session id by calling session_id().
__get($key)
21. Set.
This is also a magic function that allows you to assign items to $_SESSION by accessing them as $this->session properties.
__set($key, $value)
Codeigniter Security Class Library
Codeigniter Security Class Library -This library provide various functions that are used to create a secure application and processing input data for security. This class is also automatically loaded by the system that’s why no need to load manually. Here in this tutorial, we are going to explain how to use security class library.
Codeigniter security class library | Example
Let us understand how security class library works in codeigniter with examples.
Functions:-
Codeigniter security class library provide three types of method.
- 1. XSS Filtering.
- 2. Cross-site request forgery (CSRF).
- 3. Class Reference.
1. XSS Filtering.
Here is simple demo of XSS filtering.
Codiegniter come with a cross site scripting filter, which is commonly used technique to trigger, javascript or other type of code. It is also use to filter data through XSS filter.
Example of XSS filtering
security->xss_clean($str); echo $data; if ($this->security->xss_clean($str, TRUE) === FALSE) { echo "file failed the XSS test"; } else { return true; }}} ?> |
Output will be like this:-
2. Cross-site request forgery (CSRF).
Here is simple demo of cross-site request forgery (CSRF).
We can enable csrf protechtion from application/config/config.php file.
Example of Cross-site request forgery (CSRF).
$this->security->get_csrf_token_name('ram'), 'hash' => $this->security->get_csrf_hash('gff')); print_r($csrf); } } ?> |
Output will be like this:-
Class reference:-
There are various references available in security class library. Now we will explain.
1. XSS clean.
This reference try to remove XSS program from the input data and return cleaned string.
xss_clean($str[$is_image = FALSE])
- Parameters :
- $str (mixed) : Input string or an array of strings
- Returns : XSS-clean data
- Returns type : Mixed
2. Sanitize filename.
This reference Try to sanitize filename in order to prevent directory traversal attempt and other security threats, which is particularly useful for file that was supplied by user input.
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
- Returns type : string
3. Get csrf token name.
This reference return the csrf token name.
get_csrf_token_name()
- Parameters :
- Returns : CSRF token name
- Returns type : string
4. Get csrf hash.
This reference return the csrf hash value.
get_csrf_hash()
- Parameters :
- Returns : CSRF hash
- Returns type : string
5. Entity decode.
This reference try to detect HTML entities.
entity_decode($str[$charset = NULL])
- Parameters :
- $str (string) : Input string
- $charset (string) : Character set of the input string
- Returns : Entity-decoded string
- Returns type : string
6. Get random bytes.
This reference is used to CSRF and XSS tokens.
get_random_bytes($length)
- Parameters :
- $length (int) : Output length
- Returns : A binary stream of random bytes or FALSE on failure
- Returns type : String
Codeigniter Template Parser Class Library
Codeigniter Template Parser Class Library – We can load template parser class library like this $this->load->library(‘parser’);. This library provide various functions that are used to perform simple text for pseudo-variable contained within your view files. It can parse simple variable or variable tags pair. Here in this tutorial, we are going to explain how to use template parser class library.
Codeigniter template parser class library
Let us understand how template parser class library works in codeigniter with examples.
Load template parser class library
First load template parser class library to use its functions, this library can be loaded simply as below-
How to load template parser class library:
$this->load->library('parser'); |
Functions:-
There are following functions available in template parser class library. Now we will explain one by one.
- 1. Parsing templates.
- 2. Variable Pairs.
- 3. Usage Notes.
- 4. View Fragments.
1. Parsing templates.
Here is simple demo of Parsing templates.
First we have to create view page .
View Page Code [Folder Name : parser_view.php ]
|
Controller Code [Folder Name : parser_controller.php ]
load->library('parser'); $data = array( 'blog_title' => 'My Blog Title', 'blog_heading' => 'My Blog Heading'); echo $this->parser->parse('parser_view', $data, true); } } ?> |
2. Variable Pairs.
Here is simple demo of Variable Pairs.
Controller Code
Controller Code [Folder Name : parser_controller.php ]
load->library('parser'); $data = array('blog_title' => 'My Blog Title', 'blog_heading' => 'My First Website', 'blog_entries' => array( array('title' => 'My Blog', 'body' => 'Sonu Kumar'), array('title' => 'Contact Us', 'body' => 'sonukr321@gmail.com'), array('title' => 'Company name', 'body' => 'SolidCoupon'))); $this->parser->parse('library/parser_view', $data); } } ?> |
3. Usage Notes.
Here is simple demo of Usage Notes.
Controller Code
Controller Code [Folder Name : parser_controller.php ]
load->library('parser'); $template = 'Hello, {firstname} {initials} {lastname}'; $data = array('title' => 'Mr','firstname' => 'John', 'lastname' => 'Doe'); $this->parser->parse_string($template, $data); $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); } } ?> |
4. View Fragments.
Here is simple demo of view fragments.
Controller Code
Controller Code [Folder Name : parser_controller.php ]
load->library('parser'); $template = '
Tutorialsplane"; $data = array('menuitems' => array( array('title' => 'PHP', 'link' => '/php_page'), array('title' => 'CODEIGNITER', 'link' => '/codeigniter_page'), array('title' => 'CAKE PHP', 'link' => '/cakephp_page'), array('title' => 'BOOTSTARP', 'link' => '/bootstarp_page'))); $this->parser->parse_string($template, $data); } } ?> |
Class reference:-
There are following references available in template parser class library. Now we will explain.
1. Parse.
This reference is used to parse a template from the provided path and variables.
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
- Returns type : String
2. Parse string.
This reference work same like parse(). It only accept template as a string and loading a view file.
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
- Returns type : String
3. Set delimiters.
This method is used to set opening and closing tag for pseudo variable tags in template.
set_delimiters([$l = '{'[$r = '}']])
- Parameters :
- $l (string) : Left delimiter
- $r (string) : Right delimiter
- Returns type : void
Codeigniter Pagination Class Library
Codeigniter Pagination Class Library -We can load pagination class library like this $this->load->library(‘pagination’);. This library provides various functions that are used to create pagination class. It is 100% customizable. Here in this tutorial, we are going to explain how to use pagination class library.
Codeigniter pagination class library
Let us understand how pagination class library works in codeigniter with examples.
Load migration class library
First load pagination class library to use its functions, this library can be loaded simply as below-
How to load pagination class library:
$this->load->library('pagination'); |
Functions:-
There are following functions available in pagination class library. Now we will explain one by one.
- 1. Hiding the pages.
- 2. Adding attribute to anchors.
- 1. Disabling the “rel” attribute.
1. Hiding the pages.
Here is simple demo of hiding the pages.
This function is used to hide a pages.
load->library('pagination'); $config['base_url'] = 'http://example.com/index.php/test/page/'; $config['total_rows'] = 200; $config['per_page'] = 20; $config['display_pages'] = false; $this->pagination->initialize($config); echo $this->pagination->create_links(); } } ?> |
Output will be like this:-
2. Adding attribute to anchors.
Here is simple demo of adding attribute to anchors.
This function is used to add the attributes in pagination.
$config['attributes'] = array('class' => 'myclass'); |
3. Disabling the “rel” attribute.
Here is simple demo of disabling the “rel” attribute.
This function is used to generate dynamic relation attributes.
$config['attributes']['rel'] = FALSE; |
Class reference:-
There are following references available in pagination class library. Now we will explain.
1. Initialize.
This reference is used to initialize to pagination class.
initialize([$params = array()])
- Parameters :
- $params (array) : Configuration parameters
- Returns : CI_Pagination instance
- Returns type : CI_Pagination
2. Create links.
This reference is used to return a pagination bar.
create_links()
- Parameters :
- Returns : HTML-formatted pagination
- Returns type : string
Full example of pagination.
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(); } } ?>
Output will be like this:-
More Example About Pagination
Let us see in details about pagination example.
Pagination View Code:-
File Name-[search_result_view.php]
|
Pagination Controller Code:-
File Name-[UserController.php]
load->model('UserModel'); $this->load->helper('country_helper'); $title = $this->input->get('search'); $model = $this->load->model('UserModel'); $config['base_url'] = base_url().'index.php/userController/showlist/'; $totalRows = $this->UserModel->searchUser($title); $data['data'] = $this->UserModel->searchUser($title, $start); $config['total_rows'] = count($totalRows); $config['per_page'] = 5; //data per page you want to display. $this->load->library('pagination'); $this->pagination->initialize($config); $this->load->view('common/header_view'); $this->load->view('search_result_view',$data); $this->load->view('common/footer_view'); } } ?> |
Pagination model Code:-
File Name-[UserModel.php]
db->select('*'); $this->db->from(USERS); $this->db->like('name', $title); $this->db->or_like('uname', $title); $this->db->or_like('email', $title); $this->db->limit(10, $start); $query = $this->db->get(); $result = $query->result_array(); return $result; } } ?> |
Output will be look like this:-
Codeigniter Output Class Library
Codeigniter Output Class Library – This library provide various functions that are used to send the finalized web page to the requesting browser. When we use the loader class to load a view file. It automatically passed to the output class. This class is automatically loaded by the system that’s why no need to load manually. It also responsible for caching your web page. Here in this tutorial, we are going to explain how to use Output class library.
Codeigniter output class library
Let us understand how output class library works in codeigniter with examples.
Class reference:-
There are following references available in output class library. Now we will explain.
1. parse var.
This reference is used to enalble/disable of elapsed time and memomory usage in pseudo variables.
parse_exec_vars = TRUE;
Example.
output->parse_exec_vars = true; } } ?>
2. Set output.
This function gives permit to set final output string.
set_output($output)
- Parameters :
- $output (string) : String to set the output to
- Returns : CI_Output instance
- Returns type : CI_Output
Example.
output->set_output($data); } } ?>
Output will be like this:-
3. Set content type.
This function also give permit you to set the mime-type of your page and serve JSON data, jpeg, xml.
set_content_type($mime_type[$charset = NULL])
- Parameters :
- $mime_type (string) : MIME Type idenitifer string
- $charset (string) : Character set
- Returns : CI_Output instance
- Returns type : CI_Output
Example 1.
output ->set_content_type('application/json') ->set_output(json_encode(array('SolidCoupon' => 'Tutorialsplane'))); } } ?>
Output will be like this:-
Example 2.
output ->set_content_type('jpeg') ->set_output(file_get_contents('uploads/Hydrangeas.jpg')); } } ?>
Output will be like this:-
4. Get content type.
This function is used to return content type HTTP header which is currently in use. .
get_content_type()
- Parameters :
- Returns : Content-Type string
- Returns type : string
Example.
output->get_content_type(); echo $mime; } } ?>
Output will be like this:-
5. Get header.
This function can be used to return the requested http header value.
get_header($header)
- Parameters :
- $header (string) : HTTP header name
- Returns : HTTP response header or NULL if not found
- Returns type : Mixed
Example.
output->set_content_type('Tutorialsplane', 'UTF-8'); echo $this->output->get_header('content-type'); } } ?>
Output will be like this:-
6. Get output.
This reference permits you to transitive any output has been storage in output class.
get_output()
- Parameters :
- Returns : Output string
- Returns type : String
7. Append output.
This reference return append data in to output string.
append_output($output)
- Parameters :
- $output (string) : Additional output data to append
- Returns : CI_Output instance
- Returns type : CI_Output
Example.
output->append_output($data); } } ?>
Output will be like this:-
8. Set header.
This reference permits you to set server header.
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
- Returns type : CI_Output
Example.
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').' 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'); } } ?>
9. Set status header.
This function is used to set a server status header.
set_status_header([$code = 200[$text = '']])
- Parameters :
- $code (int) : HTTP status code
- $text (string) : Optional message
- Returns : CI_Output instance
- Returns type : CI_Output
Example.
$this->output->set_status_header(401);
10. Enable profiler.
This function is used to enable/disable the profiler. which will display benchmark and other data at the bottom of your page for debugging.
enable_profiler([$val = TRUE])
- Parameters :
- $val (bool) : Whether to enable or disable the Profiler
- Returns : CI_Output instance
- Returns type : CI_Output
Example.
output->enable_profiler(true); } } ?>
Output will be like this:-
11. Set profiler section.
This function is used to enable/disable specific section of the profiler.
set_profiler_sections($sections)
- Parameters :
- $sections (array) : Profiler sections
- Returns : CI_Output instance
- Returns type : CI_Output
12. Cache.
This function is used to enable/disable caches the current page for the specific amount of times.
cache($time)
- Parameters :
- $time (int) : Cache expiration time in minutes
- Returns : CI_Output instance
- Returns type : CI_Output
13. Display.
It sends output data to the browser with any server header. It also stop benchmark timers.
_display([$output = ''])
- Parameters :
- $output (string) : Output data override
- Returns : void
- Returns type : void
Example.
'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; } } ?>
Output will be like this:-
Codeigniter Migrations Class Library
Codeigniter Migrations Class Library – We can load image manuipulation class library like this $this->load->library(‘migration’);. This library provide various functions that are used for automatically detects and run sql queries. We make some change in database by using migration class library. Codeigniter also allow us to setup migration. Here in this tutorial, we are going to explain how to use migration class library.
Codeigniter migration class library
Let us understand how migration class library works in codeigniter with examples.
Load migration class library
First load migration class library to use its functions, this library can be loaded simply as below-
How to load migration class library:
$this->load->library('migration'); |
Functions:-
There are following functions available in migration class library. Now we will explain one by one.
- 1. Create a Migration.
- 2. Delete a Migration.
1. Create a Migration.
Here is simple demo of Create a Migration.
This function allows users to create a migration.
load->library('migration'); $this->dbforge->add_field(array( 'id' => array('type' => 'INT', 'constraint' => 5, 'unsigned' => TRUE, 'auto_increment' => TRUE), 'title' => array('type' => 'VARCHAR', 'constraint' => '100'), 'description' => array('type' => 'TEXT', 'null' => TRUE))); $this->dbforge->add_key('id', TRUE); $this->dbforge->create_table('users'); if ($this->migration->current() === FALSE) { show_error($this->migration->error_string()); } else { echo "database inserted successfully"; } } } ?> |
2. Delete a Migration.
Here is simple demo of delete a Migration.
This function allows users to delete a Migration.
load->library('migration'); $delete = $this->dbforge->drop_table('users'); if($delete==true) { echo "Migration deleted successfully"; } } } ?> |
Class reference:-
There are following references available in migration class library. Now we will explain.
1. Current.
This reference is used to set migrate up to the current version.
current()
- Parameters :
- Returns : TRUE if no migrations are found, current version string on success, FALSE on failure
- Returns type : mixed
Example.
load->library('migration'); if ($this->migration->current() === FALSE) { echo show_error($this->migration->error_string()); } else{ echo "run successfully"; } } } ?>
Output will be like this:-
2. Error string.
This function return error which is detected while performing a migration.
error_string()
- Parameters :
- Returns : Error messages
- Returns type : String
3. Find migrations.
This function returned that are found in migration path .
find_migrations()
- Parameters :
- Returns : An array of migration files
- Returns type : Array
4. latest.
This function returned that are found in migration path .
latest()
- Parameters :
- Returns : Current version string on success, FALSE on failure
- Returns type : Mixed
Example.
load->library('migration'); if ($this->migration->latest() === FALSE) { echo show_error($this->migration->error_string()); } else { echo "Latest migration run successfully"; } } } ?>
5. version.
Version function can be used to rollback changes to specific version.
latest()
- Parameters :
- $target_version (mixed) : Migration version to process
- Returns : TRUE if no migrations are found, current version string on success, FALSE on failure
- Returns type : Mixed
Example.
input->is_cli_request()) { $this->load->library('migration'); $migration = $this->migration->version($version); if(!$migration) { echo $this->migration->error_string(); } else { echo 'Migration(s) done'.PHP_EOL; } } else { echo 'You don\'t have permission for this action'; } } } ?>
Output will be like this:-
Codeigniter Loader Class Library
Codeigniter Loader Class Library – Loader class is initialized automatically by the system that’s why there is no need to do manually. This library provides various functions which are used to load elements. These elements can be library or class, Views file, Drivers, Helpers, Models or your own files. Here in this tutorial, we are going to explain how to use loader class library.
Codeigniter loader class library | Example
Let us understand how loader class library works in codeigniter with examples.
Functions:-
There are following functions available in loader class library. Now we will explain one by one.
- 1. Application “Packages”.
- 2. Package view files.
1. Application “Packages”.
Here is simple demo of application “Packages”.
Application package allows user to create own libraries, views, controller, models, helpers, config files in third party folder.
2. Package view files.
Here is simple demo of package view files.
How to create own view file see in example:-
load->add_package_path(APPPATH.'third_party/myApp', FALSE); $this->load->view('welcome_message'); } } ?> |
output will be like this
Class reference:-
There are following references available in loaded class library. Now we will explain.
1. Library.
This reference is used to only load core classes.
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
Example.
$this->load->library('email'); $this->load->library(array('email', 'table'));//load multiple library using array. $this->load->library('config', NULL, 'my_config');//we can set own name of library. $this->my_config
2. Driver.
We used this reference to load only driver library.
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
Example.
load->driver('session'); print_r($result); } } ?>
$result = $this->load->driver(array('session', 'cache')); print_r($result);
$config = array('sess_driver' => 'cookie', 'sess_encrypt_cookie' => true, 'encryption_key' => 'mysecretkey'); $result = $this->load->driver('session', $config); print_r($result);
Output will be like this of above code.
3. Views.
This reference is used to load only views page.
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.
- Return type : Mixed
Example.
$this->load->view('View_file_name'); $this->load->view('View_file_name', '', TRUE);
4. Vars.
This reference is used to check associative array as input and generate variable using php function.
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
4. Get vars.
This is use to check array of variables available in your views file.
get_var($key)
- Parameters.
- $key (string) : Variable name key
- Returns : Value if key is found, NULL if not.
- Return type : mixed
5. Clear vars.
This reference is used to clear cached views variables.
clear_vars()
- Parameters.
- Returns : CI_Loader instance (method chaining).
- Return type : CI_Loader
6. Models.
This reference is used to only load core classes.
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
Example.
$this->load->model('model_name');
7. Database.
This method is used to load the database.
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
8. Helper.
This method is used to load the helper.
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
9. File.
This is a file loading method. Put the file path and file name in first parameter. It will open and read the file.
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.
- Return type : Mixed
10. Language.
This class is an alias of the language loading method.
language($files[$lang = ''])
- Parameters.
- $files (mixed) : Language file name or an array of multiple language files
- $lang (string) : Language name
- Returns : CI_Loader instance.
- Return type : CI_Loader
11. Config.
This class is an alias of the config file loading method and return always boolean result.
config($file[$use_sections = FALSE[$fail_gracefully = FALSE]])
- Parameters.
- $files (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
12. is_Loaded.
we use this method to allows user to check whether class has been already loaded or not.
is_loaded($class)
- Parameters.
- $class (string) : Class name
- Returns : Single ton property name if found, FALSE if not.
- Return type : Mixed
Example.
$this->load->library('form_validation'); $this->load->is_loaded('Form_validation'); // returns 'form_validation'
$this->load->library('form_validation', $config, 'Loaded_library'); $this->load->library('form_validation'); $this->load->is_loaded('Form_validation'); // returns 'Loaded_library'
13. Add package path.
we use this method to load application package or adding a package path.
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.
- Return type : CI_Loader
Example.
load->add_package_path(APPPATH.'third_party/myApp', FALSE); $this->load->view('welcome_message'); } } ?>
14. Remove package path.
we use this method to removing a package path.
remove_package_path([$path = ''])
- Parameters.
- $path (string) : Path to remove
- Returns : CI_Loader instance.
- Return type : CI_Loader
Example.
load->remove_package_path(APPPATH.'third_party/myApp', FALSE); } } ?>
14. Get package paths.
Its return all availble package path.
get_package_paths([$include_base = TRUE])
- Parameters.
- $include_base (bool) : Whether to include BASEPATH
- Returns : An array of package paths.
- Return type : array
Example.
load->get_package_paths(APPPATH.'third_party/myApp', FALSE); } } ?>
Codeigniter Language Class Library
Codeigniter Language Class Library – This library provides various functions which are used to transitive language files and path of text for purpose of internationalization. We can easily create or incorporate own language files. This library provides translation of core message into another language. Here in this tutorial, we are going to explain how to use language class library.
Codeigniter language class library | Example
Let us understand how language class library works in codeigniter with examples.
Functions:-
There are following functions available in language class library. Now we will explain one by one with example.
- 1. Sample Language Files.
- 2. Example of switching languages.
- 3. Creating Language Files.
- 4. Loading A Language File.
- 5. Fetching a Line of Text.
1. Sample Language Files.
Here is simple demo of sample language files.
2. Example of switching languages.
Here is simple demo of switching language.
Syntax of switching language:-
$language = $this->session->get_userdata('english'); $this->lang->load('error_messages', $language); $oops = $this->lang->line('message_key'); |
3. Creating language files.
Here is simple demo of creating language.
Language file must be named with _lang.php as the file extension name.
Syntax of creating language:-
$lang['Welcome_message'] = 'You are welcome'; $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'; |
4. Loading a language file.
Here is simple demo of loading a language files.
Syntax of loading a language files:-
$this->lang->load('alert_language', 'english'); |
5. Fetching a Line of Text.
Here is simple demo of fetching a line of text.
Syntax of fetching a line of text:-
$this->lang->line('welcome_message'); |
EXAMPLE
Here is simple example of language class library.
Controller code:-
load->view('library/language_view'); $this->lang->load('alert_language', 'english'); echo $this->lang->line('welcome_message'); $this->lang->load('alert_language', 'hindi'); echo $this->lang->line('welcome_message'); } } ?> |
You must have created new folder with extension _lang.php in application/language folder.
Folder path: application/language/english/alert_language_lang.php
|
Folder path: application/language/hindi/alert_language_lang.php
|
The output will be like this –
Codeigniter Input Class Library
Codeigniter Input Class Library -This library contains various functions that are used to pre-process global input data for security and fetching input data. Input class library is auto-generated, no need to load this library. This class is initialized automatically to the system so no need to do it manually. Here in this tutorial, we are going to explain how to use input class library.
Codeigniter input class library
Let us understand how input class library works in codeigniter with examples.
Class reference:-
There are following references available in input class library. Now we will explain one by one.
1. Raw input stream.
This function is used to only read property of data.
$raw_input_stream()
2. Post.
This is used to post value of field.
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
EXAMPLE
Here is simple demo of post class.
$this->input->post('field_data'); $this->input->post('field_data', TRUE); $this->input->post(NULL, TRUE); $this->input->post(NULL, FALSE); $this->input->post(array('field1', 'field2'), TRUE); |
3. Get.
This is used to fetch data in get method only.
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
EXAMPLE
Here is simple demo of get class.
$this->input->get('field_data', TRUE); $this->input->get(NULL, TRUE); $this->input->get(NULL, FALSE); $this->input->get(array('field1', 'field2')); |
4. Post get.
This method works same as post and get method combined. It will search both stream but looking in POST first, and then in GET.
post_get($index[$xss_clean = NULL])
- Parameters.
- $index (mixed) : POST/GET parameter name
- $xss_clean (bool) : Whether to apply XSS filtering
- Returns : POST/GET value if found, NULL if not
- Return type : mixed
EXAMPLE
Here is simple demo of post get class.
$this->input->post_get('field_data', TRUE); |
5. Get post.
This method works same as previous method. It will search both stream but looking in GET first, and then in POST.
get_post($index[, $xss_clean = NULL])
- Parameters.
- $index (mixed) : GET/POST parameter name
- $xss_clean (bool) : Whether to apply XSS filtering
- Returns : GET/POST value if found, NULL if not
- Return type : mixed
EXAMPLE
Here is simple demo of GET/POST class.
$this->input->get_post('field_data', TRUE); |
6. Cookies.
This method is used to fetch the cookies data and display it.
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
- Returns type : String
EXAMPLE
Here is simple example of cookies class.
Controller code:-
Your controller code now look like this:-
|
Output will be like this.
7. Server.
We use this function to fetch the server data and return an array of multiple server 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
- Returns type : mixed
EXAMPLE
Here is simple demo of server class.
Controller code:-
Your controller code now look like this:-
input->server(array('SERVER_PROTOCOL', 'REQUEST_URI')); print_r($server); }} ?> |
Output will be like this.
8. Set cookies.
This method is used to set cookies containing specific value. We can pass the information in array and discreate parameters.
set_cookie($name = ''[$value = ''[$expire = ''[$domain = ''[$path = '/'[$prefix = ''[$secure = NULL[$httponly = NULL]]]]]]])
- 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)
- Returns type : void
EXAMPLE
Here is simple example of set cookies class.
Controller code:-
Array method:-:-
'cookies', 'value' => 'Tutorialsplane.com', 'expire' => '3600'); $this->input->set_cookie($cookie); echo get_cookie('cookies'); }} ?> |
Output will be like this.
9. Valid IP address.
We use this function to check IP address whether it is valid or not.
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
- Returns type : Bool
EXAMPLE
Here is simple demo of valid ip class.
Controller code:-
Your controller code now look like this:-
input->valid_ip($ip, 'ipv4')) { echo 'Not Valid'; } else { echo 'Valid'; } } } ?> |
Output will be like this.
10. User agent.
Its return all information about user web browser.
user_agent([$xss_clean = NULL])
- Parameters.
- $xss_clean (bool) : Whether to apply XSS filtering
- Returns : User agent string or NULL if not set
- Returns type : mixed
EXAMPLE
Here is simple example of user agent class.
Controller code:-
Your controller code now look like this:-
input->user_agent(); } } ?> |
Output will be like this.
11. Request header.
We use this function to return an array of HTTP request header.
request_headers([$xss_clean = FALSE])
- Parameters.
- $index (mixed) : Value name
- $xss_clean (bool) : Whether to apply XSS filtering
- Returns : An array of HTTP request headers
- Returns type : array
EXAMPLE
Here is simple demo of request header class.
Controller code:-
Your controller code now look like this:-
input->request_headers(); print_r($headers); } } ?> |
Output will be like this.
12. Method.
We use this function to set value in upper or lowercase.
method([$upper = FALSE])
- Parameters.
- $upper (bool) : Whether to return the request method name in upper or lower case
- Returns : HTTP request method
- Returns type : String
EXAMPLE
Here is simple demo of method class.
Controller code:-
Your controller code now look like this:-
input->method(TRUE); echo " |
Output will be like this.