Summarize some excellent features of CodeIgniter

Source: Internet
Author: User
Tags benchmark bulk insert how to prevent sql injection php framework php introduction server array codeigniter

Summarize some excellent features of CodeIgniter

Recently prepared to take over the improvement of a project written by someone else with CodeIgniter, although previously also useful CI, but is completely according to their own meaning written, not according to some of CI's routines. Used in public projects, it is best to follow the framework of the standard, so the sum up, lest others later take over the time laughable.

1. First, MVC

If you do not know MVC, you should learn as soon as possible, you will quickly appreciate the data access in the Model, business logic in the Controller, the value of writing HTML code in the views. If you haven't used this pattern before, you may wrinkle your forehead, but you should give yourself the chance to do so.

One rule of practice is to put fewer things in the Controller and remember the DRY rule: don't reinvent the wheel. When writing the same code in more than one place, you should try to write a library, helper, or model based on its type. For example, the database connection class, used very frequently, it is made into model (the system has been provided).

Once you understand the essence of MVC, it will become a habit, and you'll benefit from the simplicity of MVC's code.

One principle is that complex operations are given to model. The controller is more like an architect. Model is drudgery. View is a paint job. The Controller only needs to throw things into the model, and it doesn't need to care if the data is abnormal, and then returns a flag bit and the corresponding data. So the MVC architecture is reflected.

Model is actually like an electrical appliance such as: microwave oven, the simpler the use of the more people like, (put food in-press start-ok, rice cooked. The advantage of fewer interfaces is that when the model upgrade code is optimized, the coupling to the outside world is not high. Even if you write poorly inside, the interface is clean and easy to use.

2. Application and System paths

It is best to place the system and application folders outside of Webroot, if the index.php is placed under the/public_html/path of the FTP server, you should try to put the system under the root directory/system, so , you can only access your PHP files via index.php.

Do not forget to modify the values of the $system _folder and $application _folder in the index.php file, $system the value of _folder should be relative to the index.php file, and $application _folder The value is relative to the system directory.

3. Error Reporting and debugging

A common mistake is to forget to turn off PHP errors and database error reporting, which is risky. In any public site, the error_reporting should be set to 0, up to a maximum of e_error, the database settings db_debug should be set to false, based on other security considerations, the settings do not display error messages Ini_set (' Display_ Errors ', ' Off ');

When you encode and debug, you should set error_reporting to E_all and resolve every note and warning before releasing the application.

An easy way is to set the value of Db_debug in the application/config/database.php file to a constant Mp_db_debug, when the Web site is running, as follows:

Ini_set (' display_errors ', ' Off '); error_reporting (0);d efine (' Mp_db_debug ', false);

Set in encoding and debugging to:

Ini_set (' display_errors ', ' on '); error_reporting (E_all);d efine (' Mp_db_debug ', true);

4. Security issues are important

Before receiving any data to your program, whether it is a form-submitted POST data, COOKIE data, URI data, XML-RPC data, or data in a SERVER array, we recommend that you practice the following three steps:

Filtering bad data.

Verify the data to ensure that the correct type, length, size, etc. are met. (Sometimes this step can also replace the first step)

Convert the data before submitting it to your database.

With regard to SQL injection, XSS, and CSRF, you should understand them before deciding whether to use methods to prevent them. Refer to the Security Guide on the CI Manual as well as the input and security classes. Perhaps the most important principle is to check the input of all users before committing the data to the database or file system.
SQL injection. This problem can be solved by using the Active Record that comes with CI.

XSS (cross-site scripting). By setting the $config [' global_xss_filtering '] = TRUE; Turns on automatic filtering of cross-site scripting attacks in post and cookies, but consumes some resources. It can also be used separately each time the post and cookie processing, set the second parameter to TRUE, such as $this->input->post (' Some_data ', TRUE); The form validation class also provides XSS filtering options, such as $this->form_validation->set_rules (' username ', ' username ', ' trim|required|xss_clean ');

CSRF (cross-site request forgery). CI 2.0 will have a built-in CSRF check, search "CSRF tokens" on Google to learn more about protecting form submissions and URL links, and in Ajax applications you can search for "double cookie Submission" or "double commit C Ookie ".

SPAM (spam and malicious registration). By protecting your e-mail forms, commenting forms, and other free user submissions to prevent spam, an easy way is to allow only one Ip/user client to submit only once in a minute, a better way to use Captcha, A CAPTCHA helper function is built into the CI2.
5. Database and ORM

CodeIgniter has a library Active Record that can help you write query statements without using SQL statements. This is a good approach when you are not too proficient in SQL statements or do not know how to prevent SQL injection.

When you need more powerful tools, you can consider using the Object relational Mapper, which is the famous ORM, unfortunately, CodeIgniter does not have an ORM library, but there are some other good choices.

Perhaps the most popular is the Datamapper overzealous Edition (DMZ), which can also be used Doctrine (there is a tutorial here), and the other option Rapiddatamapper is the author's own work.

6. Code Practices

Write concise code, and understand your code, not just copy and paste someone else's code, and constantly improve the coding ability. The development specification on the manual is a place where you can learn how to write code better.

1. DRY. Don't always reinvent the wheel, put the reusable code where it should be, like libraries, helpers or models, rather than controllers, a rule of thumb: When you copy the code, maybe you've put it in the wrong place for the second time.

2. Caching (Cache). Caching is a great way to raise performance, especially to reduce access to the database. You can refer to the Web cache and the database cache, or search other options on the forums, such as Mp_cache, the author's own work.

3. HTTP headers (HTTP header). On the client side you can improve performance by sending the browser to cache pages individually via HTTP headers, and when you use AJAX you also need to understand it to disallow browser caching.

An example of a disallowed cache:

$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", false); $this->output->set_header ("Pragma: No-cache ");

An example of a long-kept cache (CSS, JavaScript, for example):

$this->output->set_header (' Cache-control:private, pre-check=0, post-check=0, max-age=2592000 '); $this Output->set_header (' Expires: '. Gmstrftime ("%a,%d%b%Y%h:%m:%s GMT", Time () + 2592000); $this->output->set_h Eader (' last-modified: '. Gmstrftime ("%a,%d%b%Y%h:%m:%s GMT", Time ()-20));

7. Template rendering does not have to call headers and footer each time

Add the following to the My_controller header and __CONSTRUCT functions to set the default template information, where site_name needs to define itself in application/config/constants.php:

Class My_controller extends Ci_controller {  protected $_data;    Template value array  protected $_tplext;  Default template suffix  protected $_header;  Default head template  protected $_footer;  Default bottom template public  function __construct () {      parent::__construct ();      $this->_data[' title ' = site_name;      $this->_tplext = '. php ';      $this->_header = ' templates/header ';      $this->_footer = ' templates/footer ';      Open performance analysis in development mode      if (environment = = = ' Development ') {          $this->output->enable_profiler (TRUE);}      }}  

8. It is not necessary to inherit all classes Ci_controller

The new controller no longer inherits Ci_controller, but inherits My_controller:

Class Index extends My_controller {public  function __construct () {      parent::__construct ();  }  /**   * Front page   *  /Public Function index () {      $this->_data[' title '] = ' home ';  Do not specify use default caption site_name      $this->_view (' Index/index ');}  }

Finally, add two more:
9. CodeIgniter's file Structure

The cache is used to store cached files, and the CodeIgniter folder contains the base class Ci_base for CI, with two versions for compatibility with PHP4 and Php5,ci_base, where PHP4 version ci_base inherits from Ci_loader. Libraries stores most of the commonly used class libraries, the main three classes: Model,view and Cotronller, any mvc you write to inherit from the existing MVC class, helpers is a collection of functions (methods) to assist other modules to facilitate the work. Language is a language pack that supports multiple languages.

Application Folder to store your application, CI has added some sub-files to you internally, including models, views, Controllers, config, errors, hooks, and libraries. The first three folders are used to create models, views, and controllers. Most of your work should be to create your own MVC, and you can add a config file in config, and add some objects and methods in libraries to help your model and controller work. Hooks is also an extension of ci_hooks, as detailed in the following chapters.

working process of CodeIgniter

When there is an HTTP request, such as, first enter the CI boot file index.php. Now let's look at what's going on in index.php.

Index first set the application's folder name to application, the system's folder name is systems, and then made a series of strict judgments and converted to UNIX-style server absolute file path, specifically defined two more important constants, APPPATH, The folder path of the application, according to the analysis, the path can be and system sibling: htdocs/application/, can also be placed in the System folder, as its subfolders: htdocs/system/application/, But it is recommended to use the second way, it seems more neat; basepath, the basic file path of the website document, written out is probably htdoc/system/; in the end, the index boot file was introduced into the codeigniter/codeigniter.php. Next we look at what's going on in CodeIgniter.

Codeigniter.php introduced three files: common.php,compat.php and config/constants.php, where Common contains functions for loading the Load_class of class libraries, The log_message of logging, and the introduction of error page show_404 are several important functions, compat mainly solves the problem of function incompatibility in PHP4 and PHP5, while constants defines some constants to read and write file permissions.

Immediately after CodeIgniter loaded the first class library, Benchmark, the simplest application of this class library is to calculate the time it takes to start the Web page from the beginning to the end of the compilation, so you can figure out the time it takes to make a mark at the beginning of the compilation, and then mark the end of the rendering.

Then loading the second class library, Hooks, the class library, like Benchmark, is under System\libraries, the role of this class library is to give you a chance to do other things before the program starts compiling, Hooks you to perform other tasks to provide about 8 opportunities, See the User Guide for details. Here, it imports the first hook.

Then load the Config,uri,router,output class library, and then check for cache_override hooks, which allows you to dispatch your own function to replace the _display_cache method of the output class, if not, Directly call the output of the _display_cache, check whether there is cache content, if any, the direct output of the cache, exit, if not, then proceed down.

After that, continue loading input,language, note that the previously loaded class library is a reference, and then another important load, that is, Ci_base object loading, first will determine the PHP version, if it is PHP4 version, will first load loader, and then load BASE4 , because Ci_base inherits from Ci_loader in Base4, and Ci_base has no inheritance relationship with Ci_loader in BASE5.

The next step, which is really critical, starts by loading a controller class, which is an instance, not a reference, and then parses the HTTP address through router, obtains the name of the controller and method, and then looks at application\ Controllers if there is such a controller and method, if not, then error, if any, then begin to judge.


First summed up so much, and then supplemented. Hope everyone can vote like.

Reference Source:
Several excellent features of CodeIgniter

Extended Reading

"PHP Framework CodeIgniter" series of technical Articles to organize the collection

1CodeIgniter PHP MVC Framework China website

2 How to get rid of index.php in CodeIgniter URL

Types of CodeIgniter XMLRPC classes in 3php for data exchange

4 uploading images using CodeIgniter's class library

5CodeIgniter caching mechanisms and how to use them

6 How to adjust the error level of CodeIgniter

7 User Login verification for extended CodeIgniter

8 The template mechanism for CodeIgniter plus phpcms

9CodeIgniter Framework Basic configuration file config.php Introduction

10 using native PHP to write a routing function like CodeIgniter

11 Integrated Baidu Editor in CodeIgniter Ueditor

12apache+codeigniter through. htcaccess do dynamic two-level domain name resolution

Introduction to the use of 13CodeIgniter-band database classes

14 parsing CI is the rewrite rule of CodeIgniter framework under Nginx

15php of CodeIgniter Learning notes

Deep analysis of 16CodeIgniter image processing class

17 Parsing CodeIgniter Custom configuration files

18 parsing the session of the framework using the PHP framework CodeIgniter

19 parsing how to remove index.php from the CodeIgniter URL

20CodeIgniter upload picture successful all process sharing

21PHP Open Source Framework CodeIgniter release version 2.1.1

22php CodeIgniter Frame Paging class

23CodeIgniter Basic Configuration Detailed description

24CodeIgniter using the Phpcms template engine

25CodeIgniter ways to generate sitemap maps for Web sites

26Codeigniter Easy Integration Smarty

27 Let CodeIgniter support HMVC architecture

28 Let CodeIgniter realize layout function

29codeigniter Use tips Bulk Insert data instance method sharing

30codeigniter Framework BULK INSERT data

31codeigniter Tutorial Multi-File Upload use example

32codeigniter Tutorial upload video and use ffmpeg to FLV sample

33 fix CodeIgniter cannot upload rar and zip package issues

34CodeIgniter frame _remap () Use Method 2 Example

35codeigniter self-brought database class usage description

36Codeigniter simultaneous access to paging data and total number of bars

37Codeigniter performing a large memory footprint under the CLI, ci another big hole

Example of a paged class passed in 38codeigniter

39CodeIgniter Framework Tips disallowed Key characters Solutions

40codeigniter Frame The URI you submitted have disallowed characters error resolution

41 about CodeIgniter 5 points of knowledge you may not know

42 Resolving CodeIgniter pseudo-static invalidation

43CI (CodeIgniter) Framework Introduction

Additions and deletions in 44CI (CodeIgniter) frame

45CI (CodeIgniter) frame configuration

46CodeIgniter How to enable cache and clear cache

47 How to make CodeIgniter Database cache auto-expiration processing

48Codeigniter How to realize intelligent cropping of pictures

49Codeigniter implementation of URL jumps after user login verification is processed

50 database configuration using CodeIgniter under the Sina SAE cloud Platform

51Codeigniter Integrated Tank AUTH permission class library detailed

52 The best solution for CodeIgniter and swfupload integration

53Codeigniter enables multiple file uploads and creates multiple thumbnails

54Codeigniter upload image appears "You do not have a select a file to upload" error resolution

55CodeIgniter Frame Filter HTML hazard code

56 Let CodeIgniter's Ellipsize () Support Chinese truncation method

57Codeigniter simple way to generate Excel documents

58codeigniter integrated ucenter1.6 Two-way communication solution

Two solutions to 59CodeIgniter output garbled in Chinese

How to suppress a Database error occurred error message in 60Codeigniter

61codeigniter+phpexcel implementing export Data to an Excel file

62 uploading images using CodeIgniter's class library

63 defining CodeIgniter Global variables using configuration classes

64Codeigniter error message errors with CACHE directory solution

65codeigniter Database Operation Function Summary

66Codeigniter Registering Login code example

Summary of optimization of 67Codeigniter Operational database tables

Introduction to 68CodeIgniter CLI mode

69CodeIgniter security-Related settings rollup

70CodeIgniter Implementing a method to change the View folder path

71CodeIgniter Template engine Usage examples

Three ways to use cookies in 72CodeIgniter

73CodeIgniter Multi-language Implementation using Config control automatic conversion function according to browser language

74 ways to improve the CodeIgniter code hinting function in the IDE

Implement pan domain name resolution in 75CodeIgniter

76codeigniter uploading images does not correctly identify the problem resolution of the picture type

772 codeigniter File Batch Upload Controller example

mkdir creating a directory in 78Codeigniter encounters permissions issues and workarounds

Design flaws and solutions of 79CodeIgniter framework database transaction processing

80Codeigniter Framework update transaction (transaction) bugs and workarounds

81CodeIgniter Framework URL Routing Summary

82CodeIgniter error mysql_connect (): No such file or directory workaround

Some of the best practices of 83Codeigniter

84Codeigniter (CI) framework paging functions and related knowledge

85Codeigniter Shopping Cart class cannot add Chinese solution

86Codeigniter Framework implementation method for obtaining paging data and total number of bars

Summary of some excellent features of 87Codeigniter

Some good practices of 88PHP framework CodeIgniter

89CodeIgniter method for lighttpd server URL rewriting

90CodeIgniter methods for sending HTML messages using the SMTP service

91CodeIgniter implements the method of fetching pictures from the website and automatically downloading them to the folder

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Summarize some excellent features of CodeIgniter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.