1 : CodeIgniter current version : till 11 September 2022
CodeIgniter 3 : 3.1.13.
CodeIgniter 4 : 4.2.6
2 : Explain the difference between helper and library in CodeIgniter.
Helper | Library |
---|---|
Helper is a collection of common functions which we can use within Models, Views as well as in Controllers. Once we include the helper file, we can get access to the functions. | Library is a class that has a set of functions that permits for creating an instance of that class by $this->load->library() function. |
It is not written in object-oriented format. | It is written in an object-oriented format. |
It can be called in the same manner you call PHP functions. | You must create an object of the class to call library functions by using the $this->library_name->method() . |
All built-in helper file names are suffixed with a word _helper (ex: email_helper.php ). | All built-in library files do not have a specific suffix. |
- Routing is a technique used in CodeIgniter, by which you can define your URLs based on the requirement instead of using the predefined URLs. So, whenever there is a request made and matches the URL pattern defined by us, it will automatically direct to the specified controller and function.
- A URL string and its corresponding controller class or method are in a one-to-one relationship here. The URI segments usually follow this pattern:
example.com/class/function/id/
. All routing rules are defined in theapplication/config/routes.php
file of CodeIgniter.
Codeigniter is called a loosely based MVC framework because it does not need to obey a strict MVC pattern during application creation. It is not important to create a model, we can use only view and controllers for creating an application. In addition, one can modify CodeIgniter to utilize HMVC(Hierarchical Model View Controller) as well.
5. What is a helper in CodeIgniter?
- Helpers are the group of functions that are useful in assisting the user to perform specific tasks.
- There are three types of helper files. They are:
- URL helpers: Used for creating the links.
- Text helpers: Used for the formatting of text.
- Cookies helpers: Used to read and manage cookies.
- You need to load the helper files for using it. Once loaded, it will be globally available to your controller and views. They can be obtained at two places in CodeIgniter. A helper file will be searched by CodeIgniter in the
application/helpers
folder and if it is not available in that folder then it will check in thesystem/helpers
folder. - Helper file can be loaded by adding the following code to the constructor of the controller or inside any function that wants to use:
$this->load->helper('file_name');
Write your file name at the place of file_name. - To load URL helper we can use the code given below:
$this->load->helper('url');
- You are allowed to auto-load a helper if your application needs that helper globally by including it in the
application/config/autoload.php
file. - Loading multiple helpers is also possible. For doing this, specify them in an array as given below:
$this->load->helper(
array('helper1', 'helper2', 'helper3')
);
The list of available hook points are given below:
pre_system
: It is called initially during system execution.pre_controller
: It is called immediately before any of the controllers being called. Example:
$hook['pre_controller'] = array(
'class' => 'ExampleClass',
'function' => 'Examplefunction',
'filename' => 'ExampleClass.php',
'filepath' => 'hooks',
'params' => array('mango', 'apple', 'orange')
);
post_controller_constructor
: It is called soon after instantiating your controller, but before any occurrence of the method call.post_controller
: It is called immediately after the complete execution of the controller.display_override
: It overrides the_display()
method.cache_override
: It enables calling of the user-defined method instead of_display_cache()
method which is available in the Output Library. This permits you for using your own cache display mechanism.post_system
: It is called soon after the final rendered page has been submitted to the web browser, at the end of system execution when the final data has been sent to the browser
- Libraries are packages created in PHP that give higher-level abstractions and thus contribute to faster development. This removes the necessity of focusing on small, minute details by taking care of those by themselves.
- Three methods are available to create a library:
- Create an entirely new library
- Extend native libraries
- Replace native libraries
- To load a library in CodeIgniter, you have to include the below code inside a controller:
$this->load->library(‘class_name’);
- All pre-defined libraries developed by CodeIgniter can be obtained at the
system/libraries
directory. - For loading multiple libraries at the same time, you can make use of the same code. But replace the parameter with an array for loading multiple libraries.
$this->load->library(array(‘library1’, ‘library2’));
You have to create a file with the name Example.php under application/core/
directory and declare your class with the below code:
Class Example extends CI_Input {
// Write your code here
}
Based on | Laravel | CodeIgniter |
---|---|---|
Database model | It is object-oriented. | It is relational object-oriented. |
Built-in module | It comes along with a built-in module. | It does not come with a built-in module. |
Structure | Follows MVC structure of filing with a command-line tool known as Artisan. | Follows the MVC structure but it provides easier boarding based on object-oriented programming. |
Development and Template | It is a good option for front-end developers and it comes along with the Blade template engine. | It is easier to use and there is no template engine provided. |
Utilized by | OctoberCMS, Laracasts | PyroCMS, Expression engine |
Libraries | Provide their own official documentation which is very helpful. | Provides a lot of built-in functionality |
Routing | Supports Explicit routing | Supports both Explicit and Implicit routing. |
Following Databases are supported by the CodeIgniter framework:
- MySQL (version 5.1+) database that uses MySQL (deprecated), mysqli, and PDO drivers
- Oracle database that uses oci8 and PDO drivers
- PostgreSQL database that uses Postgre and PDO drivers
- ODBC database that uses ODBC and PDO drivers
- SQLite database that uses SQLite version 2, SQLite3 version 3, along with PDO drivers
- MS SQL database that uses Sqlsrv (version 2005 and above), MsSQL, and PDO drivers
- Interbase/Firebird database that uses iBase and PDO drivers
- CUBRID database that uses Cubridand PDO drivers
CodeIgniter enables you to develop error reporting into your applications by using the below-given functions. Also, it has a class dedicated to error logging that permits messages related to error and debugging to be saved as text files.
Functions related to error handling are:
- This function will display the error message provided by the
application/errors/errorgeneral.php
template.
show_error(‘message’ [, int $statuscode= 500 ] )
- This function shows the 404 error message supplied to it by using the
application/errors/error404.php
template.
show_404(‘page’ [, ‘logerror’])
- This function permits you to write messages onto your log files. You must provide anyone among three “levels” in the first parameter that indicates the message type (debug, error, info), with the message itself in the second parameter.
log_message(‘level’, ‘message’)
- In CodeIgniter, models are loaded as well as called inside your controller methods. For loading a model, you must use the below-given method:
$this->load->model('name_of_the_model');
- Include the relative path from the directory of your model, if your model is placed inside a sub-directory. Consider an example, you have a model which is placed at
application/models/blog/AllPosts.php
you can load it by using:$this->load->model('blog/AllPosts');
- You can access the methods provided by the model, once the model gets loaded by using an object which has the same name as your controller:
class MyBlogController extends CI_Controller
{
public function MyblogModel()
{
$this->load->model('blog_model');
$data['que'] = $this->blog_model->get_last_five_entries();
$this->load->view('blog_model', $data);
}
}
A view is a webpage that shows each element of the user interface. It cannot be called directly, you need to load the views via the controller. You can pass an array from the controller to view in CodeIgniter using below given steps:
- Create a view:
Create a new text file and name it ciblogview.php
. Save the created file in the application/views/
directory. Open the ciblogview.php
file and add the below-given code to it:
<html>
<head>
<title>Blog</title>
</head>
<body>
<h1>Welcome to Blog in CodeIgniter</h1>
</body>
</html>
- Load the view:
Loading a view is executed using the following syntax: $this->load->view('name');
Where ‘name’ represents the name of the view.
The below code creates a controller named Blog.php
. This controller has the method for loading the view.
<?php
class Blog extends CI_Controller
{
public function index()
{
$this->load->view('ciblogview');
}
}
?>
- Passing an array from the controller to view:
You are allowed to paste the below-given controller code within your controller file or put it in the controller object.
$data['mega_header'][] = (object) array('title' => 'image portfolio' , 'img' => 'https://complete_image_path' );
$this->load->view('multiple_array', $data);
Arrays are displayed as a brick[‘…’] and objects as an arrow(->). You are allowed to access an array with the brick[‘…’] and object using the arrow (->). Therefore, add the below-given code in the view file:
<?php
if (isset($mega_header)){
foreach ($mega_header as $key) {
?>
<div class="header_item">
<img alt="<?php echo($key['title']); ?>" src="<?php echo($key->img); ?>"/>
</div>
<?php
}
}
?>
- Add dynamic data to views:
Usually, data transfer from the controller to view is done through an array or an object. The array or the object is passed as the second parameter of the view load method similar to the below-given method:
$data = array(
'title' => 'TitleValue',
'heading' => 'HeadingValue'
);
$this->load->view('ciblogview', $data);
The controller will look like this:
<?php
class Blog extends CI_Controller {
public function index()
{
$data['title'] = "TitleValue";
$data['heading'] = "HeadingValue";
$this->load->view('ciblogview', $data);
}
}
?>
The view file will look like this:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
</body>
</html>
In CodeIgniter, you are allowed to maintain a user’s “state” by Session class and keep an eye on their activity while they browse your website.
- Loading a session in CodeIgniter:
For using session, your controller should be loaded with your Session class by using the$this->load->library(‘session’);
.
Once the Session class is loaded, the Session library object can be obtained using$this->session
. - Read session data in CodeIgniter:
$this->session->userdata();
method of Session class is used to read or obtain session data in CodeIgniter.
Usage:$this->session->userdata('name_of_user');
Also, the below-given method of the Session class can be used to read session data.
Usage:$this->session->key_item
Where an item represents the key name you want to access. - Create a session in CodeIgniter:
The set_userdata() method that belongs to the Session class is useful in creating a session in CodeIgniter. This method uses an associative array that has the data you want to include in the session.
Adding session data:
Example:
$sessiondata = array(
'name_of_user' => 'lekha',
'email' => 'lekha@interviewbit.com',
'log_state' => TRUE
);
$this->session->set_userdata($sessiondata);
If you want to add a single user data at a time, set_userdata()
supports this syntax:
$this->session->set_userdata('demo_username', 'demo_value');
- Remove session data in CodeIgniter:
The unset_userdata() method that belongs to the Session class is useful for removing session data in CodeIgniter. Usage examples are given below:
Unset particular key:
$this->session->unset_userdata('name_of_user');
Unset an array of item keys:
$arr_items = array('name_of_user', 'email');
$this->session->unset_userdata($arr_items);
The CodeIgniter folder structure is given below:
- application: This directory will have your application logic. All of your application codes will be held in this directory. Internal subdirectories in the CodeIgniter directory structure are given below:
- cache – It stores cached files.
- config – It keeps configuration files.
- controller – All application controllers are defined under this controller.
- core – It consists of custom core classes that extend system files. For example, if you create a base controller that other controllers should extend, then you should place it under this directory.
- helpers – This directory will be used for user-defined helper functions.
- hooks – It is used for custom hooks in the CodeIgniter folder structure.
- language – It is used to store language files for applications that use multiple languages.
- libraries – It is used to store custom-created libraries.
- logs – Application log files are placed in this directory.
- models - All application models must be defined under this directory.
- third_party – This is used for custom many packages that are created by you or other developers.
- views – application views will be stored in this directory.
- system: It consists of the framework core files. It is not advised to make any modifications in this directory or put your own application code into this directory. System subdirectories in CodeIgniter are given below:
- core – This is considered to be the heart of the CodeIgniter Framework. All of the core files that construct the framework are located here. If you would like to extend the core file functionality, then you must
- create a custom core file in the application directory. After this, you are allowed to override or add new behavior that you wish. You should never make any changes directly in this directory.
- database – It stores the files such as database drivers, cache, and other files that are needed for database operations.
- fonts – This directory contains fonts and font-related information.
- helpers – This directory consists of helper functions that come out of the box.
- language – It contains language files that are used by the framework
- libraries – It contains the source files for the different libraries that come along with CodeIgniter out of the box.
- user_guide: This directory consists of a user manual for CodeIgniter. You should not upload this directory during application deployment.
- vendor: This directory consists of composer packages source code. The
composer.json
andcomposer.lock
are the other two files related to this directory. - index.php: This is considered as the entry point into the application. It is placed inside the root directory.
17. What is the security parameter for XSS in CodeIgniter?
- Codeigniter has got a Cross-Site Scripting(XSS) hack prevention filter. This filter either automatically runs or you can run it based on item, to filter all data related to POST and COOKIE.
- The XSS filter will target the frequently used methods to trigger JavaScript code or other types of code that attempt to hijack cookies or do any other malicious activity. If it identifies anything suspicious or anything disallowed is encountered, then it will convert the data to character entities.
- To filter data through the XSS filter, we will make use of the xss_clean() method as given below:
$data = $this->security->xss_clean($data);
This function is used only when you are submitting data. The second Boolean parameter is optional and used to check the image files for the XSS attacks. This is very useful for file upload. If its value is true, that means the image is safer and not otherwise.
18. What is the default controller in CodeIgniter?
- When the name of the file is not mentioned in the URL then the file will be specified in the default controller that is loaded by default. By default, the file name will be
welcome.php
, which is known as the first page to be seen after the installation of CodeIgniter. localhost/codeigniter/
In this case, thewelcome.php
will be generally loaded as the file name is not mentioned in the provided URL. Generally, the programmers can change the default controller that is present in theapplication/config/routes.php
file as per their needs.$route['default_controller'] = ' ';
In the above-given syntax, the programmer has to specify the file name that he/she wants to get loaded as the default one.
19. List all the auto-loadable resources available in CodeIgniter.
- The below-given items can be automatically loaded in CodeIgniter:
- Classes obtained in the directory named
libraries/
- Custom config files obtained in the directory named
config/
- Helper files obtained in the directory named
helpers/
- Models obtained in the directory named
models/
- Language files obtained in the directory named
system/language/
- Classes obtained in the directory named
- For resource autoloading, you should open the file
application/config/autoload.php
and include the item that you want to be get loaded into the array of autoloads. In the file related to each type of item, you can find instructions
To connect more than one database simultaneously, do the following,
In CodeIgniter, Inhibitor is an error handler class that uses native PHP functions like set_exception_handler, set_error_handler, register_shutdown_function to handle parse errors, exceptions, and fatal errors.
23 :What are the various functions used in Codeigniter?Ans: The functions in Codeigniter are globally defined and freely available. Loading of libraries or helpers is not required when using these functions.
is_really_writable($file)
is_php($version)
html_escape($var)
config_item($key)
set_status_header($code[, $text = ”])
is_https()
remove_invisible_characters($str[, $url_encoded = TRUE])
is_cli()
get_mimes()
24 : How is the default timezone set in Codeigniter?Ans: The default timezone in Codeigniter is set by opening the application using the config.php file and adding this code to it.
date_default_timezone_set('your timezone');
Ans: To link or add the images/CSS/JavaScript in Codeigniter absolute path to your resources is used.
For example
// Refers to $config['base_url']
<img src="<?php echo site_url('images/myimage.jpg'); ?>" />
26 :How to extract the last inserted id in Codeigniter?Ans: The DB Class insert_id() method is used in Codeigniter to get the last insert id.
Usage:
function add_post($post_data){
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Ans: To remove the index.php from URL in Codeigniter the following steps are used
Step 1: Open config.php and replaces
$config['index_page'] = "index.php" to $config['index_page'] = ""
and
$config['uri_protocol'] ="AUTO" to $config['uri_protocol'] = "REQUEST_URI"
Step 2: Change your .htaccess file to
RewriteEngine on
RewriteCond $1 !^(index\.php|[Javascript / CSS / Image root Folder name(s)]|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
You can use $this->db->last_query();
to display the query string.
You can use print_r($query);
to display the query result.
You can use $lastInsertID = $this->db->insert_id();
after insert query.
No comments:
Post a Comment