A summary of some outstanding characteristics of CodeIgniter _php example

Source: Internet
Author: User
Tags benchmark how to prevent sql injection server array sql injection codeigniter file permissions

Recently prepared to take over the improvement of a project that someone else wrote with CodeIgniter, although it used to be CI, but it was written in its own words, not according to some of CI's routines. In public projects, it is best to follow the framework of the norms, so still summed up, so that when others take over the time laughable.

1. First is MVC

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

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

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

One principle is that complex operations are given to model. Controller more like an architect. Model is drudgery. The View is a painting worker. Controller just want to throw things into the model can be, do not need to care about whether the data is abnormal, and then return a flag bit and the corresponding data. So the architecture of MVC is reflected.

Model in fact like a electrical appliance, such as: microwave oven, the simpler the use of the more people like, (put food in-press to start-ok, cooked rice. The advantage of less interface is that the model upgrade code optimization, the external coupling 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 Webroot, and if index.php is placed on the/public_html/path of the FTP server, try to put system in the root directory/system, so , you can only access your PHP files through index.php.

Don't forget to modify the value of the $system _folder and $application _folder in the index.php file, $system the _folder value should be relative to the index.php file, $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, error_reporting should be set to 0, up to E_error, database settings db_debug should be set to false, and for other security reasons, the setting does not display error messages Ini_set (' Display_ Errors ', ' off ');

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

An easy way to do this is to set the Db_debug value in the application/config/database.php file to a constant Mp_db_debug, when the Web site is running, the following settings:

Copy Code code as follows:

Ini_set (' display_errors ', ' off ');
error_reporting (0);
Define (' Mp_db_debug ', false);

Set in encoding and debugging to:

Copy Code code as follows:

Ini_set (' display_errors ', ' on ');
Error_reporting (E_all);
Define (' Mp_db_debug ', true);

4. Security issues are important

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

Filter 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 to your database before submitting it.
About SQL injection, XSS, and CSRF, you should understand them first, and then decide whether or not to use methods to prevent them. You can refer to the Security Guide in 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 submitting the data to the database or file system.

SQL injection. An Active record with a CI can solve this problem.
XSS (cross-site scripting). by setting $config [' global_xss_filtering '] = TRUE; Turn on automatic filtering of post and Cross-site scripting attacks in cookies, but consumes some resources. It can also be used separately each time the post and cookie are processed, setting the second argument 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 station request forgery). CI 2.0 will be built into the CSRF check, Google search "CSRF tokens" Learn more about the protection of form submission and URL links in the knowledge of Ajax applications can search "double cookie Submission" or "double submit C Ookie ".
SPAM (spam message and malicious registration). By protecting your mailing form, commenting on forms, and other free user submissions to prevent spam, a simple way is to allow only one Ip/user client to submit only once in a minute, a better way is to use Captcha, A CAPTCHA auxiliary function is built into the CI2.

5. Database and ORM

CodeIgniter has a self-contained library Active record that can help you write query statements without using SQL statements. This is a good way to do this 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 the Object relational Mapper, which is the famous ORM, and unfortunately, CodeIgniter does not own an ORM library, but there are some other good options.

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

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 capabilities. The development specification in the manual is a place to learn how to write code better.

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

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

3. HTTP headers (HTTP header). At the client you can improve performance by sending the HTTP header to the browser to cache the page, and you need to understand it to prevent browser caching when you use AJAX.

An example of a suppression cache:

Copy Code code as follows:

$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 time to keep the cache (CSS, JavaScript, for example):

Copy Code code as follows:

$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. Template rendering does not have to call header and footer every time

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

Copy Code code as follows:

Class My_controller extends Ci_controller {
  protected $_data;&nbs p;  //Template pass-value array
  protected $_tplext; //default template suffix
  protected $_header; //default header template
  protected $_footer; //default bottom template
  public function __construct () {
   &N bsp;  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. Do not need all classes to inherit Ci_controller

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

Copy Code code as follows:

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

Finally, add two more:

9. Document Structure of CodeIgniter

Cache is used to store cached files, the CodeIgniter folder contains the base class Ci_base for CI, and for compatibility PhP4 and Php5,ci_base There are two versions, where the PHP4 version of Ci_base inherits from Ci_loader. Libraries stores most of the most commonly used class libraries, the main three classes: Model,view and Cotronller, any of their own written MVC will inherit from the existing MVC class; Helpers is a collection of functions (methods) that assist in the convenience of other modules. Language is a language pack that supports multiple languages.

The application folder is used to store your applications, CI has added some of the files internally to 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 to your config, libraries adding objects and methods to help your model and controller work. And hooks is also the extension of the ci_hooks, the specific content see the following chapters.

Working process of CodeIgniter

When there is an HTTP request, such as http://www.google.com/blog/, first enter the CI's boot file index.php. Let's look at what's going on in index.php.

Index first sets the application's folder name to application, the system's folder name is systems, and then makes a series of rigorous judgments and translates to UNIX-style server absolute file paths, specifically defining two more important constants, AppPath, The path to the folder for the application, which, according to the analysis, can be used with system siblings: htdocs/application/or in the System folder as its subfolders: htdocs/system/application/, But the second way is recommended, so it looks more neat; basepath, the basic file path of the website document, written out presumably is htdoc/system/; to the end, the index boot file is introduced into the codeigniter/codeigniter.php. Next let's 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 the class library, The log_message of logging and the introduction of the show_404 of error pages are several important functions; Compat mainly solves the problem of incompatible functions in PHP4 and PHP5, while constants defines some constants for reading and writing file permissions.

Shortly thereafter, CodeIgniter loads the first class library, Benchmark, the simplest application of this class library is to calculate the amount of time that a Web page spends from the beginning to the end of the compilation, so you can calculate the time it takes to make a mark at the beginning of the compilation, and then mark the end of the rendering.

Then load the second class library, Hooks, which is the same as benchmark in system\libraries, the role of this class library is to give you an opportunity to perform other things before the program starts compiling, and Hooks will provide you with about 8 opportunities to perform other tasks, See the user's Guide specifically. Here, it imports the first hook.

Then load the class library of Config,uri,router,output, then check if there is a cache_override hook, this hook allows you to schedule your own functions to replace the output class _display_cache method, if not, Direct call to output _display_cache, check if there is cache content, if so, direct output cache, exit, if not, then proceed down.

Thereafter, continue to load the input,language, note that the previously loaded class library is a reference, and then an important load, that is, Ci_base object loading, first of all, will determine the version of PHP, if it is PHP4 version, will first load loader, and then load the 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 the key, is to start loading a controller class, which is an instance, not a reference, and then router to resolve the HTTP address, get the name of the controller and the method, and then look at the application\ Controllers if there is such a controller and method, if not, then the error, if there is, then start to judge.

Summary

summed up so much first, later there is a supplementary. Hope everyone can vote like.

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.