Welcome to the php5.2 era!

Source: Internet
Author: User
Tags apc spl openssl library php cli sapi zip extension postgresql client
Post: www. yanbin. org20061207welcome_to_php_5_2 has been released on July 6, November 2 after N jumps and waits. According to the unwritten development habits of the PHP team, the PHP5.0 series is more like a technology demonstration version, with low performance (or even worse than PHP4, this mainly comes down to the more powerful and more complex OO mechanism in Zend) post: http://www.yanbin.org/2006/12/07/welcome_to_php_5_2/
PHP 5.2 was officially released on August 1, November 2 after N jumps and waits. According to the unwritten development habits of the PHP team, the PHP 5.0 series is more like a technology demonstration version, with low performance (or even worse than PHP4, this is mainly due to the more powerful and more complex OO mechanism in Zend, and the lack of stability. At present, the PHP development team has abandoned the development of this series. The PHP 5.1 series focuses on performance improvement, which is different from the PHP 5.0 series. However, with the release of the PHP5.2 series, PHP5.1 has entered the maintenance status like PHP4.4, and will not be updated unless there are major bugs and security risks. In addition to fixing more than 5.2 bugs in the past, the newly released PHP 200 further improves the performance, especially in high load situations, in addition, the security processing has also been greatly improved. At the same time, a lot of useful technologies (such as JSON and Zip support) have been added, and some features originally set to PHP6 have been implemented in advance in this version. It can be said that, compared with the original PHP5 version, this change is almost semi-revolutionary (the revolutionary adjective is, of course, left to PHP6's J ). I have some information and understanding below, and I will try to introduce the new features of PHP 5.2 to you. if there are any improper features, I hope you can make an axe at home:
1. the most obvious reason is that PHP 5.2 has added four new extensions while removing filePRo and hwapi extensions (the two are moved to PECL: date, JOSN, Filter, and ZIP.

In fact, from PHP 5.1, a Date extension has been added to the PHP core, rewriting support for Date/time (mainly in the time zone. The difference is that PHP 5.2 goes further, and the date and time zone become an object like DateTime and DateTimeZone respectively. You can run PHP-rc DateTime or php-rc DateTimeZone in php CLI to view the details of these two classes. It should be noted that if your program already has a DateTime or DateTimeZone class, you must change the name if you want to run it in PHP 5.2. (The well-known open-source CRM: vtigercrm already has a foresight)
JSON extension supports lightweight data exchange formats such as javaScript Object Notation (JSON. In PHP 5.2, this extension is enabled by default.
I believe that many developers are worried about the communication between PHP and Javascript, especially in the popular Ajax era. Now, we can easily solve this problem with JSON. JSON data can be used directly for the server code, and the client JavaScript can be simply read through eval (), which greatly simplifies the development of the server and client code. Although some JSON classes were also supported in PHP in the past, which of the following Native PHP support is efficient and fast? The Filter extension is used to verify and Filter data. this extension is designed to process unreliable data such as user input. This extension is also enabled by default. By default, the RAW mode will not affect the input data in any way, that is, it will not affect the existing code. However, in future development, we should try to use this extension to filter sensitive characters, because it not only simplifies some form verification work, it also improves program security and operation efficiency. The ZIP extension allows us to read and write the Zip package and the files in the package. That is to say, we can not only view the Zip file, but also touch it: it provides full support for the Zip file. This feature is widely used, and I will not talk about the specific advantages.

Of course, for details about these extensions, please refer to our omnipotent PHP Manual. : D

2. improved the memory manager to deliver better performance under high loads.
According to one of the "two old Zend", that is, the "nd" in "Zend", this new memory manager is hierarchical. This manager has three layers: storage, heap, and emalloc/efree. The storage layer uses functions such as malloc () and mmap () to apply for memory from the system, and releases the applied memory through the free () function. The storage layer is equivalent to Zend's own "memory warehouse". Generally, the applied memory blocks are relatively large. Heap layer (note that the heap here is not the heap managed by the operating system, but the memory heap managed by the Zend memory manager) they are separated from the storage layer into smaller blocks. The emalloc/efree layer refers to the memory applied for and released by the emalloc ()/efree () function of the php api. Emalloc () does not directly deal with the storage layer, but is connected to the heap layer. It allocates less memory than the original manager under the same conditions, but the speed is faster. It will first apply for some large memory blocks from the system (heap), and then manage the heap on its own. Php. although the memory_limit value in ini is still checked for use, it is no longer used for every emalloc () call, but only used when applying for large memory blocks from the system.
A friend who is familiar with programming on the server may immediately think of a word: memory pool! Yes, this is basically a memory pool. At least I think so. : D

The memory pool technology is very common in server programming. The memory pool technology can effectively avoid frequent memory application/release operations. in the memory pool technology, the actual release and recovery of the operating system are not actually notified when the memory is released, instead, it only marks the memory to be released, indicating that the memory is no longer used. When the memory is applied for the next time, a memory block is retrieved from the "available" memory linked list, which avoids frequent memory application/release operations and greatly saves system resources. According to tests and statistics, in PHP 4.4, a typical simple request has more than 20,000 application and release operations on the system heap, this takes about 20% of the total script time. It can be seen that if this resource consumption can be reduced, the effect will be extremely impressive.
At the same time, the adoption of the memory pool technology also brings a more important "side effect": to avoid a large number of "memory fragments ". In general, memory fragmentation has little impact on the system, but the server application is obviously different from the general application, and the server will face a very large number of access requests, these requests are also accompanied by more memory application/release operations. Too many memory fragments will reduce the memory usage and reduce the memory allocation speed. in severe cases, memory allocation will also fail, even though theoretically there will still be allocable physical memory.
Finally, the memory pool technology has an unnoticeable advantage: it can reduce the probability of memory leakage. Because the size of the actually applied memory block is large, but the quantity is small, and generally it is applied for in a unified manner. in actual release, it can also be released in a unified manner. Obviously, this is much lower than the probability of memory leakage caused by instant application in the code without immediate release.

However, the manager using the memory pool technology is significantly more overhead than the regular manager (referring to the memory instant application and instant release management mechanism, in addition to the actually applied memory, the manager must maintain the status of each memory block. in ini, the memory_limit command value is increased from the default 8 M to 16 M. This seems to increase memory consumption and requires a very small amount of CPU resources for management. However, because the reduction of memory fragments does not actually increase much consumption, it can be combined with other performances, it can be said that the income is far greater than the loss, especially in the case of high load.
3. PHP 5.2 has also optimized the access to INI commands.
PHPer knows that in PHP scripts, we can use the ini_set () function to dynamically change the value of a PHP command. But the problem is that after the request ends, you have to restore the changed values to ensure that the next script can be used correctly. Before PHP 5.2, PHP had to work tirelessly to traverse and restore INI commands one by one. If you use ini_set () for the entire script (of course, this situation is extremely rare. :)) In case my script is rarely used or even does not use this function at all, isn't it a loss? Therefore, in order to solve this problem, PHP 5.2 has added an additional command to save the changed table, so that it does not need to be restored one by one.
4. PHP 5.2 also optimizes the require_once () and include_once () functions.

Before PHP 5.2, the require_once () and include_once () operations are based on fopen (), regardless of whether a file has been cached or compiled, after opening the file, check whether the file has been cached. The reason for this is that before PHP 5.1, it was not a perfect solution to the problems of realpath () relative paths and symbolic connections. If you cannot uniquely and correctly determine the true path representation of a path, you cannot use the uniqueness of the path to solve a problem. Fopen does not have this concern. This problem of realpath () was completely solved in PHP 5.1, but the results were delayed until now before it could be applied to require_once () and include_once. The advantage of solving this problem is to avoid the I/O operation of fopen. in many high-load scenarios, databases, networks, or disk I/O, rather than CPUs, are usually the bottlenecks.
5. HashTable replication is also optimized.
HashTable is a basic data structure in ZendEngine, and an array is essentially a HashTable. Optimization of HashTable also means that the speed of the array copy operation (whether explicit or implicit) will be improved.

6. Other performance improvements.
PHP 5.2 has also slightly optimized the performance of accessing environment variables in the FastCGI SAPI module. In the past, it was a row-by-row search, and now it is accessed through the Hash value. In addition, PHP 5.2 also optimizes str_replace (), implode (), and "try {} catch {}" blocks. The following are some improvements to the language and security features:

1. after PHP 5.0 adds an E_STRICT error report level (with a constant value of 2048), PHP 5.2 also adds an error report level: E_RECOVERABLE_ERROR, with a constant value of 4096.
Errors at this level are mainly captured from E_ERROR but can be captured by custom error handlers (usually specified by the set_error_handler () function. If an E_RECOVERABLE_ERROR is not captured and processed, it performs the same way as E_ERROR in all PHP versions, causing program suspension. In the error log, errors of this type will be recorded as "caught fatal error )".

The situation that causes PHP to throw E_RECOVERABLE_ERROR usually refers to situations that are dangerous but not enough to cause the Zend Engine to crash. For example, there is the following code:
Class foo {
Function bar (foo $ ){}
}

$ A = new foo;
$ A-> bar (new stdClass );
Obviously, the bar function of the class foo requires a parameter of the foo type, but the actual code gives a parameter of the stdClass type. Before PHP 5.2, this will cause an E_ERROR (Fatal error: Argument 1 passed to foo: bar () must be an instance of foo ......). However, in PHP 5.2 (including PHP6 in the future), an E_RECOVERABLE_ERROR (Catchable fatal error: Argument 1 passed to foo: bar () must be an instance of foo…) occurs ......). This error can be captured. if you specify an error processing function through set_error_handler () (even if you do not process E_RECOVERABLE_ERROR in this function), the program will continue to run. However, if you do not specify an error handler function, the E_RECOVERABLE_ERROR will be the same as E_ERROR, and the program will be terminated immediately.

2. correspondingly, the error report level E_ALL will also contain the above E_RECOVERABLE_ERROR.
This means that the constant E_ALL value will change from 2047 to 6143. Note: Although E_STRICT is added in PHP 5.0 and PHP 5.1, E_ALL does not include E_STRICT in these two versions. In later versions (such as PHP5.2 and PHP6), E_ALL includes all error levels including E_STRICT and E_RECOVERABLE_ERROR. In PHP 5.0/5.1, if we want to set error_reporting to E_ALL, we have to use error_reporting (E_ALL | E_STRICT). This is extremely awkward and may cause some negligence and misleading. In PHP5.2, we don't have to worry about this. In addition, if your configuration file in Apache (such as httpd. conf) or. in the htaccess file, the error report level is set with error_reporting (for example, php_value error_reporting 4095). because Apache does not support PHP constants, you have to manually adjust the values at the error report level.
3. added the allow_url_include ini Command to assist in the allow_url_fopen operation. this is one of the major security updates of PHP 5.2. With this command, we can differentiate between standard file operations and inclusion operations on remote files. We usually need to perform the previous standard operations, while the subsequent include operations are usually the birthplace of danger. Starting from PHP 5.2, your local script can perform standard remote file operations without remote inclusion. In fact, this is the default configuration. PHP 5.2 divides the original allow_url_fopen command into two commands: allow_url_fopen and allow_url_include. If the allow_url_fopen operation is disabled, the allow_url_include operation is also disabled. By default, the allow_url_fopen operation is allowed, but the allow_url_include operation is disabled. This effectively prevents remote code injection ). This was originally intended to be added to PHP6, and we have used it in advance. : D
4. added support for mandatory checks on the constructor type (signature) in the docking port in PHP 5.2.
Starting from PHP 5.2, if you declare a constructor in an interface, all classes that implement this interface must contain a constructor, and the constructor must be exactly the same as the constructor signature of the interface. The term "signature" here refers to the type of function parameters and return values (including the language type and whether it is reference transfer or value transfer). This concept is somewhat similar to the "prototype" in C language ".
See the following code:
Interface constr {
Function _ construct ();
}

Class implem implements constr {
Function _ construct ($ ){
}
}
This code runs in PHP5.0 and PHP 5.1, but in PHP 5.2 it will throw an error: Fatal error: Declaration of implem :__ construct () must be compatible with that of constr ::__ construct (), prompting that the constructor of implem class does not match the constr declaration of the constr interface.
It is worth mentioning that the process of adding this new feature is very interesting ., Interested friends can go to the Zend Weekly Summary (http://www.zend.com/zend/week/week279.php#Heading9) inside to see the ins and outs, here will not go into detail.
5. The _ toString () function will be called in any suitable place.
The magic method _ toString () is now called in a string context. In other words, an object can be used as a string anywhere, as long as it implements the _ toString () function. Of course, the _ toString () function you implement cannot throw an exception, otherwise the script will stop running. In the past, PHP 5.0/5.1 used to take the object Id as a string to return if necessary. this feature has been abandoned in PHP 5.2. Therefore, the problem may be that the identifier of an object is always unique. If you use the uniqueness of object identifiers in your program, this will be a defect. If the _ toString () function of the class is not implemented, but its object is used as a string, it will lead to a "capturing fatal error ". Another special case is that the object cannot be used as an array index or key name, even if it has a _ toString () method. In the future, PHP may build a Hash mechanism to provide support for object uniqueness. However, for now, you must provide an object hash algorithm by yourself, or simply use the new SPL function: spl_object_hash ();
6. added an E_NOTICE error prompt for the returned value of _ get () in write mode.
Obviously, the _ get () function can return only one value in read mode, and cannot write a value into the _ get () function. However, in previous versions, there was no prompt for this incorrect usage. Starting from PHP 5.2, an E_NOTICE will be thrown for this situation. Note: If you take the same operation for foreach () and some other functions that change the internal pointer of the array (that is, assign a value to the value extracted by foreach ), it will also trigger an E_NOTICE, because the extracted values are all in read mode. If this is the case in your code, you should convert the return value of the _ get () function into an array, or use ArrayObject in SPL to replace this array.
7. the abstract static class functions are discarded.
Due to a "pen leak", PHP 5.0 and 5.1 allow classes to have abstract static functions, but it cannot work now. Currently, only abstract static functions are allowed for interfaces.
8. other language features changed:
-SPL adds Regex Iterators and CSV support for file objects (SplFileObject.
-Added support for RFC2397 (data stream.
-Added support for Apache 2.2.
-Now you can get the file upload progress in real time during File upload.
-Update and upgrade the OpenSSL library, PCRE library, MySQL client library, PostgreSQL client library, and SQLite library required for PHP or its extension.

Finally, let's introduce the changes to the PHP running mode:
1. first, PHP 5.2 changes the priority of the PHPRC environment variable in the Win32 environment.
In the previous search for php. ini, the path sequence is as follows:
· Position specified by the SAPI module (PHPIniDir command in Apache 2,-c command line option in CGI and CLI, php_ini parameter in NSAPI, and PHP_INI_PATH environment variable in THTTPD)
· HKEY _ LOCAL_MACHINE \ SOFTWARE \ PHP \ IniFilePath (Windows Registry location)
· PHPRC environment variables
· Current working directory (for CLI)
· Web server directory (for SAPI module) or PHP Directory (for other Windows scenarios)
· Windows directory (C: \ windows or C: \ winnt ), or the position specified by the-with-config-file-path option during compilation. now the PHPRC environment variable changes from the third priority to the second priority, which is higher than the position specified by the Windows registry.
2. PHP command line mode (cli sapi) no longer looks for php. ini or php-cli.ini files in CWD (current working directory.
An undisclosed feature in PHP 5.1.x is that CLI will automatically search for the PHP configuration file in the current directory. This random reading of an unauthorized configuration file may lead to an unpredictable error. This feature has been removed in PHP 5.2 and no longer looks for php. ini or php-cli.ini files in CWD (current working directory.

Summary:
In general, PHP 5.2 has surpassed PHP4.x in terms of performance to become the fastest version at present, and it does not have its own right in terms of language and security features. Even if PHP4.x has some code caching tools (such as eAccelerator) that can improve performance, however, at present, APC and X-Cache are available to support Version 5.2 (eAccelerator may take some time to complete ). Although the performance of APC and other products is slightly inferior to eAccelerator, the optimization measures of PHP5.2 are at least not inferior to those of PHP4 + eAccelerator. Moreover, there are terrible security updates. In this case, what is the reason for us not to upgrade? At the same time, I also recommend that major VM vendors update their servers (at least new servers) to PHP5.2. Without increasing the performance consumption, we can provide more language features for our customers and enhance the competitiveness of our products. why not?
Let's start the PHP 5.2 era!

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.