PHP Development Specification

PHP Development Specification mainly describes the coding style used to develop the CodeIgniter framework itself. It is recommended to use these specifications in your code.

File Format

The file needs to be saved as Unicode (UTF-8). BOM should not be used. Unlike UTF-16 and UTF-32, UTF-8 encoded files do not need to specify the endianness, and the BOM will produce unexpected output in PHP, preventing the application from setting its own header information. The Unix format line ending character (LF) should be used.

Here is how to change these settings in some common text editors. For your editor, the method may be different; please refer to the instructions of your editor

Notepad++

  • Open Application Preferences
  • Click Advanced, click the “Saving” tab
  • In “File Encoding”, select “UTF-8 (recommended)”
  • In “Line Endings”, select “LF (recommended)”
  • Optional Check “Use for existing files as well”, if you want to modify the end of file, open your new reference.

PHP closing tag

The PHP closing tag “?>” is optional for the PHP parser in PHP. However, if you use closed tags, any spaces after the closed tags inserted by developers, users, or FTP applications may cause redundant output, php errors, subsequent output failure to display, and blank pages. Therefore, all php files should omit this php closing tag and insert a comment to indicate that this is the bottom of the file and locate the relative path of this file in this application. This helps you make sure that the file is closed and not truncated.

Named file

The name of the class file is capitalized, while other file names (configuration, view, script, etc.) must be all lowercase

Wrong :

somelibrary.php
someLibrary.php
SOMELIBRARY.php
Some_Library.php

Application_config.php
Application_Config.php
applicationConfig.php

Correct :

Somelibrary.php
Some_library.php

applicationconfig.php
application_config.php

In addition, the class file name must be the same as the class name. For example, if you have another class Myclass, its file name must also be Myclass.php

Class and Method Naming

The name of the class must begin with an uppercase letter, and use underscores to separate words, not camel case style.

Error :

class superclass
class SuperClass

Correct :

class Super_class
class Super_class {

    public function __construct()
    {

    }
}

Class methods must be all lowercase, the name can clearly express the function of the function, it is best to include verbs. Try to avoid names that are too long and verbose. Use underscores to separate words.

Error :

function fileproperties()       // not descriptive and needs underscore separator
function fileProperties()       // not descriptive and uses CamelCase
function getfileproperties()        // Better!  But still missing underscore separator
function getFileProperties()        // uses CamelCase
function get_the_file_properties_from_the_file()    // wordy

Correct :

function get_file_properties()  // descriptive, underscore separator, and all lowercase letters

Variable Name (PHP Development Specification)

PHP Development Specification also depends on the naming rules for variables are very similar to the naming rules for methods. That is to say, the variable name should contain only lowercase letters, separated by underscores, and can appropriately indicate the purpose and content of the variable. Those short, meaningless variable names should only be used as iterators in for() loops.

Error :

$j = 'foo';     // single letter variables should only be used in for() loops
$Str            // contains uppercase letters
$bufferedText       // uses CamelCasing, and could be shortened without losing semantic meaning
$groupid        // multiple words, needs underscore separator
$name_of_last_city_used // too long

Correct :

for ($j = 0; $j < 10; $j++)
$str
$buffer
$group_id
$last_city

Comment (PHP Development Specification)

Generally speaking, the code needs comments as much as possible. Not only can it help the novice to describe the process and the purpose of the code clearly, it also allows you to quickly start looking at the code in a few months. Note is not mandatory, but the following form is recommended.

Documentation block comments should be written before the declaration of classes and methods so that they can be captured by the integrated development environment (IDE):

/**
 * Super Class
 *
 * @package Package Name
 * @subpackage  Subpackage
 * @category    Category
 * @author  Author Name
 * @link    http://example.com
 */
class Super_class {

/**
 * Encodes string for use in XML
 *
 * @param   string  $str    Input string
 * @return  string
 */
function xml_encode($str)

/**
 * Data for class manipulation
 *
 * @var array
 */
public $data = array();

When using line comments, leave a blank line between the large comment block and the code.

// break up the string by newlines
$parts = explode("\n", $str);

// A longer comment that needs to give greater detail on what is
// occurring and why can use multiple single-line comments.  Try to
// keep the width reasonable, around 70 characters is the easiest to
// read.  Don't hesitate to link to permanent external resources
// that may provide greater detail:
//
// http://example.com/information_about_something/in_particular/

$parts = $this->foo($parts);

Constant (PHP Development Specification)

In addition to using all capitals for constant naming, the other rules are the same as for variables. When appropriate, always use CodeIgniter constants, such as LASH, LD, RD, PATH_CACHE, etc.

Error :

myConstant  // missing underscore separator and not fully uppercase
N       // no single-letter constants
S_C_VER     // not descriptive
$str = str_replace('{foo}', 'bar', $str);   // should use LD and RD constants

Correct :

MY_CONSTANT
NEWLINE
SUPER_CLASS_VERSION
$str = str_replace(LD.'foo'.RD, 'bar', $str);

TRUE, FALSE, and NULL

The TRUE , FALSE , and NULL keywords must be all uppercase.

Error :

if ($foo == true)
$bar = false;
function foo($bar = null)

Correct :

if ($foo == TRUE)
$bar = FALSE;
function foo($bar = NULL)

Logical Operation

It is not recommended ||, because the recognition is low on some devices (much like the number 11). &&Than ANDbetter, !before and after should add a space.

Error :

if ($foo || $bar)
if ($foo AND $bar)  // okay but not recommended for common syntax highlighting applications
if (!$foo)
if (! is_array($foo))

Correct :

if ($foo OR $bar)
if ($foo && $bar) // recommended
if ( ! $foo)
if ( ! is_array($foo))

Compare return value and type mapping

Some PHP functions return FALSE when they fail, but they may also return “” or 0, which will be calculated as FALSE in loose comparisons. When using these return values ​​in a conditional statement, in order to ensure that the return value is the type you expect and not a value with a loose type, please make an explicit comparison.

Follow this strict method when returning and checking your own variables, using === and !== when necessary.

Error :

// If 'foo' is at the beginning of the string, strpos will return a 0,
// resulting in this conditional evaluating as TRUE
if (strpos($str, 'foo') == FALSE)

Correct :

if (strpos($str, 'foo') === FALSE)

Error :

function build_string($str = "")
{
    if ($str == "") // uh-oh!  What if FALSE or the integer 0 is passed as an argument?
    {

    }
}

Correct :

function build_string($str = "")
{
    if ($str === "")
    {

    }
}

Debug code

Do not leave debugging information when submitting the code, even if it is commented. var_dump()print_r()die()exit()Do not appear in your code, unless there is a special purpose.

Spaces in the file

There should be no spaces after the PHP opening tag signature and closing tag. Since the output has been cached, the spaces in the file will cause CodeIgniter to start output before outputting its own content, which will cause CodeIgniter to make an error and fail to send the correct header.

compatibility

The recommended version of CodeIgniter is 5.4+, but it also needs to be compatible with PHP 5.2.4. Your code must be version compatible, or provide appropriate filing, or make selective features.

Do not use PHP functions that rely on non-default installed libraries, unless your code includes alternative methods when the function is not available.

One file one class

Each class has a separate file, unless these classes are closely related. The Xmlrpc library in CodeIgniter is a file with multiple classes.

Space

Use tab as indentation in yours, not spaces. This is a small thing, but it allows other developers to read your code using their favorite indentation and can be adjusted in their own IDE. Another advantage is that using a tab can replace at least 4 spaces, so the file is smaller.

Wrap

The file must use Unix line breaks. This rule is more biased towards windows users. In short, make sure your editor uses unix line break.

Code Indentation

Except for class declarations, All man style indentation is used. The braces are always on a single line and have the same indentation format as the control statement they belong to. (PHP Development Specification)

Error :

function foo($bar) {
    // ...
}

foreach ($arr as $key => $val) {
    // ...
}

if ($foo == $bar) {
    // ...
} else {
    // ...
}

for ($i = 0; $i < 10; $i++)
    {
    for ($j = 0; $j < 10; $j++)
        {
        // ...
        }
    }

try {
    // ...
}
catch() {
    // ...
}

Correct :

function foo($bar)
{
    // ...
}

foreach ($arr as $key => $val)
{
    // ...
}

if ($foo == $bar)
{
    // ...
}
else
{
    // ...
}

for ($i = 0; $i < 10; $i++)
{
    for ($j = 0; $j < 10; $j++)
    {
        // ...
    }
}

try 
{
    // ...
}
catch()
{
    // ...
}

Bracket Spacing

Generally speaking, parentheses should not have extra spaces, but some control structures that require parentheses to accept parameters (declare, do-while, elseif, for, foreach, if, switch, while) should be followed by spaces to facilitate Function difference, increase readability.

Error :

$arr[ $foo ] = 'foo';

Correct :

$arr[$foo] = 'foo'; // no spaces around array keys

Error :

function foo ( $bar )
{

}

Correct :

function foo($bar) // no spaces around parenthesis in function declarations
{

}

Error :

foreach( $query->result() as $row )

Correct :

foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis

Localized Text

The CodeIgniter library needs to use the corresponding language files this also comes under PHP Development Specification.

Error :

return "Invalid Selection";

Correct :

return $this->lang->line('invalid_selection');

Private methods and variables

Methods and variables that can only be accessed internally, such as tools and auxiliary functions, must begin with an underscore.

public function convert_text()
private function _convert_text()

PHP Error

There should be no errors in the code, and the goal cannot be achieved by hiding warnings and reminders. When variables are not used to create their own (for example, $_POSTan array of key), with the first isset()check is available.

Make sure your development environment allows all users to report errors, and enable display_errors in the PHP environment. You can check like this:

if (ini_get('display_errors') == 1)
{
    exit "Enabled";
}

In some servers display_errors is disabled, and you have no way to modify php.ini, you can usually enable it like this:

ini_set('display_errors', 1);

Note: When using a run ini_set()to set display_errors That error occurred when the program is significant, will not have any effect.

Short Mark

Always use PHP full tags to avoid the server does not support short tags, that is, short_open_tag is not opened.

Error :

<? echo $foo; ?>

<?=$foo?>

Correct :

<?php echo $foo; ?>

Note: Since PHP 5.4, the <?= tag can always be used .

One statement per line

Never write multiple statements on one line

Error :

$foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);

Correct :

$foo = 'this';
$bar = 'that';
$bat = str_replace($foo, $bar, $bag);

String

Always use single quotes unless you need to parse variables. If you need to parse variables, use braces to avoid variable parsing errors. If the string contains single quotes, you can use double quotes so that there is no need to escape.

Error :

"My String"                 // no variable parsing, so no use for double quotes
"My string $foo"                // needs braces
'SELECT foo FROM bar WHERE baz = \'bag\''   // ugly

Correct :

'My String'
"My string {$foo}"
"SELECT foo FROM bar WHERE baz = 'bag'"

SQL query

SQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.

Splitting longer statements into multiple lines can increase readability. It is best to put each clause on one line

Error :

// keywords are lowercase and query is too long for
// a single line (... indicates continuation of line)
$query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses
...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100");

Correct :

$query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz
                FROM exp_pre_email_addresses
                WHERE foo != 'oof'
                AND baz != 'zab'
                ORDER BY foobaz
                LIMIT 5, 100");

Default function parameters

When appropriate, provide default values ​​for function parameters, which helps prevent PHP errors caused by incorrect function calls. In addition, providing common alternative values ​​can save a few lines of code. For example:

function foo($bar = '', $baz = FALSE)

Security Features of CodeIgniter

This chapter describes the “best practices” for Web security, and details the internal security features of CodeIgniter.

URI security

CodeIgniter strictly limits the characters contained in the URI, allowing you to design programs to reduce the possibility of malicious data intrusion. The URI generally only contains the following:

  • Letters and numbers (Latin characters only)
  • Tilde: ~
  • Percent sign:%
  • Point:.
  • Colon::
  • Underscore: _
  • Minus sign:-
  • Space

Register_globals

System initialization time, all global variables are unset, except those $_GET$_POST$_REQUESTand $_COOKIEthe array was content. In fact, the unsetting example program has the same effect as register_globals = off.

display_errors

In a production environment, you usually disable PHP error reporting by setting the display_errors value to 0. It can disable PHP error output, it may contain sensitive information.

Setting the ENVIRONMENT constant in index.php to’production’ will close these errors. In the development mode, try to use’development’. For more details about the development environment and production environment, refer to the “Processing Environment” document.

magic_quotes_runtime

When the system is initialized, the magic_quote_runtimecommand is turned off so that the backslash does not have to be removed when the database retrieves data.

Best Practices

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

  • Filter bad data.
  • Verify the data to ensure the correct type, length, size, etc. (sometimes this step can also replace the first step)
  • Transcode before submitting data to the database

CodeIgniter provides the following functions and tips to help you complete this process:

XSS filtering

CodeIgniter comes with a cross-site scripting filter that will find malicious Javascript embedded in your data by common means, or other codes that try to trick cookies into doing other malicious things. A detailed description of XSS Filter can be found in the security document.

Note: XSS filtering only works during output. Filtering the input data may modify the original data, which is not what we want, such as stripping special characters from the password, we would rather reduce security than replace it.

CSRF protection comes under Security Features of CodeIgniter

CSRF stands for Cross-Site Request Forgery. The attacker deceives the victim to submit a request to a place he does not know.

CodeIgniter provides CSRF protection for immediate use. It will automatically trigger every non-Get HTTP request, but it also requires you to create your own submission form in some form. For details, see the document “Security Library”.

Password handling

In applications, password handling is very critical.

Unfortunately, many developers don’t know how to deal with it, and many web pages are outdated or full of errors.

We will give you a list of what you can and cannot do to help you:

  • Do not store the password in text format, you must hash the password.
  • Do not use Base64 or similar encoding to store passwords. This is the same as storing the password in text format. Be sure to hash , not encode. Encoding and encryption are two processing methods. The password must be known to you, so you can only do this. The hash algorithm is irreversible.
  • Do not use weak hashing algorithms such as MD5 or SHA1. These algorithms are outdated and flawed, so they are not good algorithms for password hashing. At the same time, don’t invent your own hash algorithm. Must use a strong hash algorithm, such as BCrypt, which is PHP’s own hash function. Please use them, even if your PHP version is not 5.5+, the minimum version provided by CodeIgniter is 5.3.7 (if your version does not meet the requirements, please upgrade). If you cannot upgrade to the new version, please use the hash_pbkdf() function, which also provides compatible algorithms.
  • Do not send the password in clear text! Even for the password owner, if the “forgot password” function is used, a random one-time password is regenerated and sent to the user.
  • Do not set unnecessary restrictions on the password. If the hash algorithm you use is not BCrypt (it is limited to 72 bits in length), you must set the password to a relatively large number of digits to resist Dos attacks, such as 1024 bytes. There is no need to restrict the password to be characters or numbers, it can contain special characters.

Verify input data

The “form validation library” in CodeIgniter can help you validate, filter, and prepare data.

Even if these things do not work, you have to verify and sanitize all input data. For example, if you want to enter must be a number that you can use is_numeric()or ctype_digit()to check.

It should be noted, not only for the inspection $_POSTand $_GETvariables, but also check the cookies, user-agent string and that the underlying data is not your code created.

Escape all data before inserting into the database

Do not insert the data before escape into the database. For more details, please refer to the document database query .

Hide your files (Security Features of CodeIgniter)

Another safe practice is to keep only index.php and “resources” (such as .js css and image files) in the root directory of your server (usually named “htdocs/”). These files are all files needed to access the website.

Let your visitors see anything, they may access sensitive data, execute scripts, etc.

If you don’t prohibit this, you can try to use .htaccess files to restrict access to these resources.

CodeIgniter will have an index.html file in all files. You can try to hide a part of it, but you should be aware that none of these can stop advanced attackers.

PHP alternative syntax for view files

If you don’t use CodeIgniter’s template syntax, you can use the original PHP code in the view file. To minimize the PHP code in these files and make them easy to identify, it is recommended that you use PHP alternative syntax to control the structure and short tag echo statements. If you are not familiar with this syntax, the following content will let you eliminate braces and “echo” statements.

Automatic short label support

Note: If you find that the syntax described on this page does not work on your server, it may be because your PHP ini file has disabled “short tags”. CodeIgniter will selectively rewrite and run the syntax you use, if your server does not support it. You can turn on this feature in the config/config.php file.

Please note that if you use this feature, if a PHP error appears in your view file, the error message and line number will not appear accurately. Instead, all errors will be shown as eval()an error.

Replace Echo

Echo, or print a variable, can be written like this:

<?php echo $variable; ?>

Using the replacement syntax, you can write:

<?=$variable?>

Alternative control structure

Control structures like if, for, foreach, and while can also be written in simplified form. Here is an example using foreach:

<ul>

<?php foreach ($todo as $item): ?>

    <li><?=$item?></li>

<?php endforeach; ?>

</ul>

Note that there is no braces, it is endforeachreplaced. Each of these control structures have the same end of the grammar: endifendforendforeach, and endwhile.

At the same time, it should be noted that after each structure, no semicolon (except for the last one), use a colon, this is very important!

Here’s another example, use ifelseifelseNote colon ::

<?php if ($username === 'sally'): ?>

    <h3>Hi Sally</h3>

<?php elseif ($username === 'joe'): ?>

    <h3>Hi Joe</h3>

<?php else: ?>

    <h3>Hi unknown user</h3>

<?php endif; ?>

Handling multiple environments

Developers usually want different behaviors in development and production environments. For example, error messages are useful in development, and the latter may cause some security problems when the project is launched.

ENVIRONMENT constant

By default, CodeIgniter the environment constant $_SERVER['CI_ENV']set to ‘development’, at the top of index.php, you’ll see:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

The server variables can be set in the .htaccess file, or use Apache SetEnvsettings. This method is valid for nginx or other methods, or you can remove this logic entirely and set a constant based on the server IP.

In addition to affecting the behavior of the basic framework (see the next chapter), you can use this constant in your development environment to distinguish it from different environments.

Impact on default frame behavior

Where are the ENVIRONMENT constants used in the CodeIgniter system. This section describes how the default system framework behavior is affected.

error report

Setting the environment variable to’development’ will cause all PHP errors to be output to the browser. Conversely, if set to’production’, error output will be disabled. It is a good security strategy to prohibit error output in the product.

Configuration file

Optionally, you can let CodeIgniter load a specific environment configuration file. This might be useful for things like managing multiple environments using different API keys. This is explained in detail in the “Environment” section of the document configuration class.

Manage Your Application

By default, you will only use CodeIgniter to manage one application, which is located in the application/ folder. Of course, it is also possible that multiple programs share a CodeIgniter, or even rename or change the path to application/.

Rename application folder
If you want to rename the application folder, you can open the index.php file and use the variable $application_folder to set its name.

$application_folder = 'application';

Change the application folder path You can move the application folder to a different location on the server instead of the root directory. Open index.php and set the $application_folder variable to the full path of the server:

$application_folder = '/path/to/your/application';

Run multiple applications under one CodeIgniter If you want multiple applications to share a CodeIgniter, you can put all the folders under application in different application folders.
applications/foo/ 
applications/foo/config/ 
applications/foo/controllers/ 
applications/foo/libraries/ 
applications/foo/models/ 
applications/foo/views/ 
applications/bar/ 
applications/bar/config/ 
applications/bar/controllers/ 
applications/bar/libraries/ 
applications/bar/models/ 
applications/bar/views/
To select an application, you need to open the index.php file and set the $application_folder variable. For example, if you choose to use the "foo" program, you can do this:

$application_folder ='applications/foo';

Note: Each application needs its own index.php file, which will call the corresponding application. You can name index.php arbitrarily.

Execute CodeIgniter via CLI

In addition to calling the controller through the browser URL, it can also be called through the command line interface (CLI).

What is CLI?

The command line interface is a text-based way of interacting with computers. For more information, refer to the Wikipedia article .

Why use the command line to run?

There are many reasons to run CodeIgniter from the command line, but they are always ignored.

  • Use cron to run tasks regularly without wget or curl
  • By examining $this->input->is_cli_request()your cron tasks can not be accessed through the Web site to let
  • Allow interactive tasks to set permissions, clear cache, perform backups, etc.
  • Integrate with other languages. For example, a C++ script can call an instruction to run the code in your model!

Let’s try: Hello World!

Let’s create a simple control so you can see how it works. Using your text editor, create a file Tools.php and add the following code:

<?php
class Tools extends CI_Controller {

    public function message($to = 'World')
    {
        echo "Hello {$to}!".PHP_EOL;
    }
}

Save the file to the application/controllers/ folder.

Now you can access it through your website URL under normal circumstances:

example.com/index.php/tools/message/to

In addition, we can also open the terminal in mac/linux, or run “cmd” in Windows, and enter the directory of our CodeIgniter project.

$ cd /path/to/project;
$ php index.php tools message

No problem if you do, you will see the Hello World! .

$ php index.php tools message "John Smith"

Here we pass a parameter to it like a URL parameter. The “John Smith” parameter is passed in, and the output becomes:

Hello John Smith!

That’s it!

In short, this is all you need to know about using controllers on the command line. Remember this is just a normal controller, so routing and _remap will work as well.

Application Performance Analysis

Benchmark results, run the query parser class will be displayed, and $_POSTdata in your footer. This information is very useful in development, it can help you debug and optimize.

Initialization class

Note: This class does not need to be initialized. If it has been activated in the following way, it will be automatically loaded by the output class.

Start the analyzer

Set the following method in the controller to start the analyzer.

$this->output->enable_profiler(TRUE);

After the analyzer is launched, a report will be generated and inserted at the bottom of your page.

Use the following methods to disable the analyzer:

$this->output->enable_profiler(FALSE);

Set reference point

In order for the analyzer to compile and display your benchmark data, you must name the benchmarks with a specific syntax.

For more details, please refer to the document “benchmark library”

Enabling and disabling segments of the analyzer

You can enable or disable each field in the analysis data by setting the corresponding control variable TRUE or FALSE. It can be achieved by one of the following two methods. One way is that you can set the global default value of the entire program in the application/config/profiler.php configuration file. E.g:

$config['config']          = FALSE;
$config['queries']         = FALSE;

In your controller, you can call set_profiler_sections()to override the default value and profile method.

$sections = array(
    'config'  => TRUE,
    'queries' => TRUE
);

$this->output->set_profiler_sections($sections);

The following table lists the available analyzer data fields and the keys used to access these fields.

Default key valuedescriptionDefaults
benchmarksTime spent at each timing point and total timeTRUE
configCodeIgniter configuration variablesTRUE
controller_infoThe called method and the controller class it belongs toTRUE
getAll GET parameters passed in the requestTRUE
http_headersHTTP header of this requestTRUE
memory_usageMemory consumed by this request (byte as a unit)TRUE
postAll POST parameters passed in the requestTRUE
queriesList the executed database operation statements and the time consumedTRUE
uri_stringURI of this requestTRUE
session_dataData is stored in the current sessionTRUE
query_toggle_countSpecify how many database query statements to display, and the rest are folded by default.25

Note: Disabling the document setting in your database configuration will effectively disable database query performance analysis. You can use $this->db->save_queries = TRUE;override this setting. Without this setting, you cannot view the query or last_query.

Web Page Caching

CodeIgniter can cache web pages to maximize performance.

Although CodeIgniter is fast enough, the dynamic content in the web page, the host’s memory CPU, and the database reading speed directly affect the loading speed of the web page. Through web page caching, your web pages can reach the loading speed of static pages because all the output has been saved.

How does the cache work?

CodeIgniter allows single page caching, and you can also set the caching time. When the page is first loaded, the file will be saved to the cache application/cachefolder. On the next visit, the cached page will be retrieved and sent to the user’s browser. If it expires, it will be deleted and regenerated.

Note: The Benchmark tag is still valid in the cached page.

Allow caching

Put the following code in your controller method to enable caching.

$this->output->cache($n);

Parameter $nis the number of minutes to cache invalidation.

The above code can be put in any method. The sequence will not affect, so you can customize the position yourself. Once the tags are set, your page will begin to cache.

Note: Due to the way CodeIgniter stores cache files, only the output from the view file can be cached.

Note: If you change the configuration option will affect the output, you need to manually delete the cache file.

Note: Before saving the cache file, please make sure that the application/cache folder is writable.

Delete cache

If you no longer need the cache, you can delete the tag so that it will no longer be cached after it becomes invalid.

Note: Deleting a tag does not delete the cache file immediately. It will be deleted after it expires.

If you need to manually delete the cache, you can use the delete_cache()method.

// Deletes cache for the currently requested URI
$this->output->delete_cache();

// Deletes cache for /foo/bar
$this->output->delete_cache('/foo/bar');

Error Handling

CodeIgniter allows you to use the following functions to create error reports in your application. In addition, it has an error log class that allows errors and debugging information to be saved as text files.

Note: By default, CodeIgniter displays all PHP errors. You may want to change this behavior after development is complete. You can find at the top of index.php error_reporting()function. Even if error reporting is disabled, the error log will not stop when an error occurs.

CodeIgniter is different from other systems. The error reporting function is a simple program interface that can be used throughout the application. Regardless of the scope of the class or function, this method can directly trigger the error notification.

Whenever the system core is called exit(), CodeIgniter will also return a status code. The exit status code is independent of the HTTP status code. This service monitors whether the execution of other applications is completed successfully, and if it is not successful, what caused it. These values ​​are defined in application/config/constants.php . The exit status code is very useful in CLI settings. The returned status code allows the server software to track the script code and make your program more robust.

The following functions can generate errors for you:

show_error($message, $status_code, $heading = 'An Error Was Encountered’)

  • Parameter mix $message: error message
  • Parameter integer $status_code: HTTP status code
  • Parameter string $heading: error page header
  • Return type: void

This function will use the following template to display error messages:

    application/views/errors/html/error_general.php

or

    application/views/errors/cli/error_general.php

Optional parameters $status_codeto determine what will happen to the HTTP status code error. Such as $status_codeless than 100, HTTP status code will be set to 500, the exit status will be set to: $status_code + EXIT__AUTO_MIN. If this value is greater than EXIT__AUTO_MAX, or if $status_codegreater than a value equal to 100, the exit code will be set EXIT_ERROR. For more details, refer to application/config/constants.php .

show_404($page = '', $log_error = TRUE)

  • Parameter string $page: URI string
  • Parameter bool $log_error: whether to write errors to the log
  • Return type: void

This function will display the 404 error message using the following template:

    application/views/errors/html/error_404.php

or

    application/views/errors/cli/error_404.php

This function hopes that the incoming string is a file path that is not found. The exit status code will be set to EXIT_UNKNOWN_FILE. Note that if no controller is found, CodeIgniter will automatically display a 404 message. CodeIgniter automatically converts any show_404()calls logged. Setting the second parameter to FALSE will skip the log.

log_message($level, $message, $php_error = FALSE)

  • Parameter string $level: log level’error’,’debug’ or’info’
  • Parameter string $message: the message written to the log
  • Parameter bool $php_error: Whether to write native PHP errors to the log
  • Return type: void

This function allows you to write messages to the log. You must provide one of the three log levels of the first parameter, which indicates what kind of message the log is written, and the second parameter is the message to be written. E.g:

    if ($some_var == '')
    {
        log_message('error', 'Some variable did not contain a value.');
    }
    else
    {
        log_message('debug', 'Some variable was correctly set');
    }

    log_message('info', 'The purpose of some variable is to provide some value.');

There are three message types:

  • Error messages. Such as PHP errors or user errors
  • Debugging information. Information to aid debugging. For example, if a class has been initialized, you can record this information.
  • Common message. This is the lowest level message, but simply provides some runtime information

Note: To write logs, you need to make sure that the logs/ folder is writable. In addition, the “threshold” in application/config/config.php must be set . For example, you can write only the error log, but not the other two logs. If you set it to 0, logging will be disabled.

Compatibility Function

CodeIgniter provides a set of compatibility functions that allow you to use non-native PHP functions, but only in higher versions or depending on an extension.

As a customized implementation, these functions also have certain dependencies, but they are still useful if your installed PHP does not provide native functions.

Note: Most and the 通用函数like, as long as the dependency is satisfied, compatibility functions have been available.<div class="custom-index container"></div>

Hash password

This set of functions provides a “backport” of the PHP standard “Hash Password Extension”, which is only available after PHP 5.5.

Dependence

  • PHP 5.3.7
  • CRYPT_BLOWFISH stand by crypt()

constant

  • PASSWORD_BCRYPT
  • PASSWORD_DEFAULT

Function reference

password_get_info($hash)

  • Parameter string $hash: hash password
  • Returns: hashed password information
  • Return type: array

For more information, please refer to PHP password_get_info()

password_hash($password, $algo[, $options = array()])

  • Parameter string $password: text password
  • Parameter integer $algo: Hashing algorithm
  • Parameter array $options: Hashing parameters
  • Returns the hashed password, or FALSE on failure
  • Return type string

For more information, reference is available PHP password_get_info() 使用手册.

Note: Unless you provide your own (valid) salt, this function can be further provided depending on the available CSPRNG source. Meet each of the following conditions:

    - ``mcrypt_create_iv()`` with ``MCRYPT_DEV_URANDOM``
    - ``openssl_random_pseudo_bytes()``
    - /dev/arandom
    - /dev/urandom

password_needs_rehash()

  • Parameter string $hash: hash password
  • Parameter integer $algo: hash algorithm
  • Parameter array $options: hash parameters
  • Return TRUE if the hash conforms to the given algorithm and parameters, return TRUE, otherwise return FALSE
  • Return type bool

For more information, please refer to PHP password_needs_rehash() 使用手册.

password_verify($password, $hash)

  • Parameter string $password: plain text password
  • Parameter string $hash: hash password
  • Return TRUE if the password and hash match, return TRUE, otherwise return FALSE.
  • Return type bool

For more information, please refer to PHP password_verify() 使用手册

Hash (message digest)

This layer contains the compatibility hash_equals()and hash_pbkdf2()function of the public key, are also required in addition to PHP 5.6 and / or 5.5.

rely

  • no

Function reference

hash_equals($known_string, $user_string)

  • Parameter string $known_string: known string
  • Parameter string $user_string: string provided by the user
  • Returns TRUE if the string matches, otherwise FALSE
  • Return type string

For more information, please refer to PHP hash_equals() 使用手册.

hash_pbkdf2($algo, $password, $salt, $iterations[, $length = 0[, $raw_output = FALSE]])

  • Parameter string $algo: hash algorithm
  • Parameter string $password: password
  • Parameter string $salt: hash salt
  • Parameter integer $iterations: the number of executions in the iteration process
  • Parameter integer $length: the length of the output string
  • Parameter bool $raw_output: whether to return the original secondary data
  • Return the encrypted value on success, FALSE on failure
  • Return type string

For more information, please refer to PHP hash_pbkdf2()

Multibyte string

This set of compatibility functions provides limited support for multibyte string expansion. Because of the limited alternatives, only a few functions are available.

Note: When a character parameter is omitted, it can be used $config['charset'].

Dependence

  • iconv extension

Note: This dependency is optional, this function is always declared. If iconv is not available, they will fall back to the non-mbstring version.

Note: When providing character setting, it must be supported by iconv and its recognized format.

Note: You should check when mbstring extension, you can use MB_ENABLEDconstants.

Function reference

mb_strlen($str[, $encoding = NULL])

  • Parameter string $str: input string
  • Parameter string $encoding: character set
  • Returns the number of characters in the input string, returns FALSE on failure
  • Return type string

For more information, please refer to the PHP mb_strlen() manual .

mb_strpos($haystack, $needle[, $offset = 0[, $encoding = NULL]])

  • Parameter string $haystack: The string to be searched
  • Parameter string $needle: Need to search for part of the string
  • Parameter integer $offset: search offset
  • Parameter string $encoding: character set
  • Returns the position of the $needle character, or FALSE on failure
  • Mixed return types

For more information, please refer to the PHP mb_strpos() manual .

mb_substr($str, $start[, $length = NULL[, $encoding = NULL]])

  • Parameter string $str: input string
  • Parameter integer $start: position of the first character
  • Parameter integer $length: the maximum number of characters
  • Parameter string $encoding: character set
  • Returns a string starting from $start and having a length of $lengthPortion. If it fails, it returns FALSE.
  • Return type string

For more information, please refer to the PHP mb_substr() manual .

Standard function

This set of compatibility functions provides some standard PHP function support, but requires a new version of PHP.

Dependence

  • no

Function reference

array_column(array $array, $column_key[, $index_key = NULL])

  • Parameter array $array: the source array of the result
  • Parameter mix $column_key: the key of the column that takes the result
  • Parameter mix $index_key: the key of the return value
  • Return to retrieve a column array from a multidimensional array
  • Return type array

For more information, please refer to the PHP array_column() manual .

array_replace(array $array1[, ...])

  • Parameter array $array1: the array to be replaced
  • Parameter array…: The array whose content needs to be advanced
  • Return the modified array
  • Return type array

For more information, please refer to the PHP array_replace() manual .

array_replace_recursive(array $array1[, ...])

  • Parameter array $array1: the array to be replaced
  • Parameter array…: the array whose content will be extracted
  • Return the modified array
  • Return type array

For more information, please refer to the PHP array_replace_recursive() manual .

Note: Only native PHP functions can detect infinite recursion. Unless your PHP version is 5.3+, you need to use the message.

hex2bin($data)

  • Parameter array $data: hexadecimal data
  • Return the two-level representation of the parameter
  • Return type string

For more information, please refer to the PHP hex2bin() manual .

quoted_printable_encode($str)

  • Parameter string $str: input string
  • Return 8bit-encoded string
  • Return type string

For more information, please refer to the PHP quoted_printable_encode() manual .