Some excellent practices of codeigniter

Source: Internet
Author: User
Tags how to prevent sql injection server array browser cache codeigniter

Recently, I was ready to take over and improve a project written by someone else using codeigniter. Although I have used CI before, I did not follow the CI routines. For public projects, it is best to follow the framework specifications, so we should sum up, so that you do not have to smile when others take over again. Fortune international entertainment city

1. MVC

If you do not know MVC, you should learn it as soon as possible. You will soon experience the value of data access in the model, business logic in the controller, and HTML code in views. If you haven't used this mode to write programs before, you may frown, but you should give yourself the chance to try it.

One practice principle is to put less things into the controller. Remember the dry principle: do not duplicate 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, if the database connection class is frequently used, it is made into a model (provided by the system ).

Once you understand the essence of MVC, it will become a habit and you will benefit from the simple code of MVC.

One principle is that complicated operations are handed over to the model. The Controller is more like an architect. Model is hard work. View is a fresh worker. The Controller only needs to throw things into the model. It does not need to care whether the data is abnormal or not, and then returns a flag and corresponding data. In this way, the MVC Architecture is reflected.

The model is actually like an electric appliance, such as a microwave oven. The simpler it is to use it, the more people like it. (put the food in and press start-OK to cook it .) The advantage of fewer interfaces is that the model upgrade code is not highly coupled with the outside world. Even if you write poorly internally, the interface is clean and easy to use.

2. Application and system paths

It is best to place the System and Application folders outside webroot, if the index. put php In the/public_html/path of the FTP server. Try to put the system in the root directory/system. In this case, you can only use index. PHP accesses your php file.

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

3. Error Reporting and debugging

A common mistake is to forget to close PHP errors and database error reports. This is risky. In any public site, error_reporting should be set to 0 and can only be set to e_error at most. db_debug should be set to false for database settings. Based on other security considerations, ini_set ('display _ errors ', 'off ');

When coding and debugging, you should set error_reporting to e_all, and resolve every note and warning before releasing the application.

A simple method is to set the db_debug value to a constant mp_db_debug in the application/config/database. php file. When the website is running, set the following:

ini_set(‘display_errors‘, ‘Off‘);error_reporting(0);define(‘MP_DB_DEBUG‘, false);  

In encoding and debugging, set it:

ini_set(‘display_errors‘, ‘On‘);error_reporting(E_ALL);define(‘MP_DB_DEBUG‘, true);  
4. Security issues are important

Whether it's post data, cookie data, Uri data, XML-RPC data, or data in the server array before receiving any data to your program, we recommend that you perform the following three steps:

  1. Filter bad data.
  2. Verify the data to ensure that it meets the correct type, length, size, and so on (sometimes this step can replace step 1)
  3. Convert the data before submitting it to your database.

For SQL injection, XSS, and csrf, you should first understand them and then decide whether to adopt methods to prevent them. Refer to the security guide and input and security classes in the CI manual. Perhaps the most important principle is to check all user input before submitting data to a database or file system.

  • SQL Injection. Use the active record that comes with CI to solve this problem.
  • XSS (XSS ). By setting $ config ['Global _ xss_filtering '] = true; Enable automatic filtering of cross-site scripting attacks in post and cookie, but it consumes some resources. You can also set the second parameter to true when processing the post and cookie, for example, $ this-> input-> post ('some _ data', true ); the Form Verification 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 be built into the csrf check, search for "csrf tokens" on Google to learn more about protection of Form submission and URL links, for Ajax applications, you can search for "Double cookie submission" or "double-submit cookie ".
  • Spam (spam and malicious registration ). Protect your email forms, comment forms, and other data submitted by various free users to prevent spam information, A simple method is to allow only one IP/user client to be submitted only once in one minute. A better way is to use CAPTCHA. CI2 has a built-in CAPTCHA helper function.
5. Databases and ORM

Codeigniter has a built-in library active record that helps you write query statements without using SQL statements. This is a good method if you are not familiar with SQL statements or do not know how to prevent SQL injection.

When you need more powerful tools, you can consider using object relational mapper, which is the most famous Orm. Unfortunately, codeigniter does not have its own ORM library, however, there are also some other good options.

The most popular one is datamapper overzealous edition (DMZ). You can also use doctrine (here is a tutorial), and rapiddatamapper is the author's work.

6. Code practice

Write concise code and understand your code. Do not just copy and paste other people's code, and constantly improve the coding capability. The development specification in the Manual is a place where you can learn how to better write code.

1. Dry. Do not always duplicate the wheel and place reusable code where it should be, such as libraries, helpers or models, rather than controllers. An Empirical principle: When you copy code, maybe you have put it in the wrong place for the second time.

2. caching ). Caching is a good way to improve performance, especially reducing database access. You can refer to the webpage cache and database cache, or search for other optional solutions on the Forum. For example, mp_cache is the work of the author.

3. HTTP headers (HTTP header ). On the client side, you can independently send an HTTP header to make the browser cache pages to improve performance. When you use Ajax, you also need to know it to disable browser cache.

An example of disabling Caching:

$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 keeping the cache for a long time (such as CSS and JavaScript ):

$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_header(‘Last-Modified: ‘ . gmstrftime("%a, %d %b %Y %H:%M:%S GMT", time() - 20));  
7. You do not need to call header and footer every time for template rendering.

Add the following content to the my_controller header and the _ construct function to set the default template information. The site_name must be defined in application/config/constants. php:

Class my_controller extends ci_controller {protected $ _ data; // template passed value array protected $ _ tplext; // default template suffix protected $ _ header; // default header 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 '; // environment = 'development ') {$ this-> output-> enable_profiler (true );}}}
8. All classes do not have to inherit ci_controller

The new controller no longer inherits ci_controller, but my_controller:

Class index extends my_controller {public function _ construct () {parent ::__ construct ();}/*** front-end homepage */Public Function Index () {$ this-> _ DATA ['title'] = 'homepage '; // if this parameter is not specified, use the default title site_name $ this-> _ view ('index/Index ');}}

At last, add two more:

9. codeigniter file structure

Cache is used to store cached files. The codeigniter folder contains the CI base class ci_base. To be compatible with PhP4 and PhP5, ci_base has two versions. ci_base of PhP4 inherits from ci_loader. Libraries stores most of the commonly used class libraries. The main three classes are model, view, and cotronler. Any self-written MVC must inherit from the existing MVC class; helpers is a set of functions (methods) to help other modules work conveniently. Language is a language pack that supports multiple languages.

The application folder is used to store your applications. CI has added some sub-files for you, 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 configuration file in config, Libraries add some objects and methods to help your model and controller work. Hooks is also an extension of ci_hooks. For details, see the following section.

10. codeigniter's Working Process

When there is an HTTP request, such as, the first to enter the cided boot file index.php. Next, let's take a look at what is done in index. php.

Index first sets the application's folder name as application, and the system's folder name as system, and then makes a series of strict judgments and converts them to the absolute file path of a Unix-style server, specifically, two important constants, apppath, and application folder path are defined. According to the analysis, the path can be the same as that of system: htdocs/application /, you can also put it in the system folder as its sub-Folder: htdocs/system/application/, but the second method is recommended, which looks neat; basepath, the basic file path of the website document, the output is probably htdoc/system/; At the end, the index guide file introduces codeigniter/codeigniter. PHP. Next, let's take a look at what codeigniter has done.

Codeigniter. PHP introduced three files: Common. PHP, compat. PHP and config/constants. PHP, the common contains some functions, which are used to load the load_class of the class library, record the log_message of the log, and introduce the show_404 of the error page; compat mainly solves the issue of function incompatibility between PhP4 and PhP5, while constants defines constants for reading and writing file permissions.

Then codeigniter loads the first class library, benchmark. The simplest application of this class library is the time spent on computing webpages from the beginning to the end of compilation, therefore, you can add a mark at the beginning of the compilation, and then add a mark after the rendering is complete to calculate the time spent.

Then the second class library, hooks, is loaded. This class library, like benchmark, is under System \ libraries, the function of this class library is to provide you with an opportunity to execute other things before the program starts compilation. Hooks will provide you with about 8 opportunities to execute other tasks. For details, see the user guide. Here, it imports the first hook.

The class libraries such as config, Uri, router, and output are loaded respectively. Then, check whether there are cache_override hooks, this hook allows you to schedule your own functions to replace the _ display_cache method of the output class. If not, you can directly call the _ display_cache method of the output class to check whether there is any cached content. If yes, then the cache is output directly and exited. If not, the cache is executed.

After that, continue to load the input and language. Note that the previously loaded class libraries are all references. Then, another important load is the loading of the ci_base object. First, the PHP version will be determined, if it is in PhP4, the loader is first loaded and then loaded to base4, because ci_base in base4 inherits from ci_loader, while in base5, ci_base has no inheritance relationship with ci_loader.

The next step is really a key step. This step starts to load a controller class, which is an instance rather than a reference. Then, the HTTP address is resolved through the router, obtain the name of the controller and method, and then check whether such controller and method exist in Application \ controllers. If not, an error is returned. If yes, start to judge.

Some excellent 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: 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.