Some good practices of codeigniter

Source: Internet
Author: User
Tags benchmark how to prevent sql injection server array 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 array of values     protected $_tplext;  //  Default template suffix     protected $_header;  //  default header template      protected $_footer;  //  Default Bottom Stencil         public  function __construct  ()  {        parent::__construct ();          $this->_data[' title '] = site_name;          $this->_tplext =  '. php ';          $this->_header =  ' Templates/header ';         $ this->_footer =  ' Templates/footer ';                 //  Development Mode Open Performance Analysis         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 the 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 http://www.google.com/blog/, 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.


Summary


First summed up so much, and then supplemented.


Some good practices 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: info-contact@alibabacloud.com 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.