PHP Technology development skills sharing _php skills

Source: Internet
Author: User
Tags php language php and php source code zend
1. Improve PHP's operational efficiency
One of the advantages of PHP is that the speed of the general Web application, can be said to be enough. However, if the site's access is high, with narrow or other factors causing the server performance bottlenecks, you may have to think of other ways to further improve PHP speed.
1.1. Code optimization
1, replace i=i+1 with I+=1. It is more efficient to conform to the C + + habit.
2. Use PHP internal function as much as possible. Write your own function before you need to consult the manual to see if there are related functions, otherwise thankless.
3, can use single quotation mark string to use single quote string as far as possible. Single quote strings are more efficient than double quote strings.
4, using foreach instead of while traversing the array. When traversing an array, foreach is significantly more efficient than the while loop and does not need to call the Reset function. The two traversal methods are as follows:
Program 1:
Copy Code code as follows:

Reset ($arr);
while (list ($key, $value) = each ($arr)) {
echo "Key: $key; Value: $value\n ";
}

Program 2:
Copy Code code as follows:

foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value\n ";
}

1.2. Compress the page
The HTTP1.1 protocol supports page compression transmission, which means that the server sends a page compression to the client, and then the page is uncompressed and then displayed to the client. There are two modes of transmission on the server side, one is that the page has been compressed in advance, as long as the transfer of compressed pages to the client on the line, this applies to static web more cases, but for most sites, dynamic page more, this method is not very suitable, because many uploaded to the client page is not actually, Is the server receives the client user request dynamic generation, therefore requests each generation to generate each dynamic page to be before uploads to the client first packs the compression. After PHP version 4.0.4, you can add a row to the php.ini file to configure "Output_handler = Ob_gzhandler" so that each dynamically generated page is compressed before it is delivered to the client, but according to the PHP official site instructions, This parameter cannot be used at the same time as the "zlib.output_compression = on" parameter, because it is easy to cause PHP to work abnormally, in addition it can only compress the dynamically generated pages of the PHP program, for a large number of static pages, especially image files. But the Mod_gzip module for Apahe provides the static page to the client before the compression of the function, its compression than the maximum can to 10, under normal circumstances can to 3, that is, the site's transmission rate increased by three times times more. To use Mod_gzip, you also have to configure Apache appropriately, and you need to include some parameters in the httpd.conf file:
Copy Code code as follows:

mod_gzip_on Yes (module is in effect)
Mod_gzip_minimum_file_size 1002 (Minimum compressed file size)
Mod_gzip_maximum_file_size 0 (Maximum compressed file size, 0 means no limit)
Mod_gzip_maximum_inmem_size 60000 (maximum memory footprint)
Mod_gzip_item_include file ". Gif102sina>double_quotation (file with GIF end to compress transfer)
Mod_gzip_item_include file ". txt102sina>double_quotation
Mod_gzip_item_include file ". html102sina>double_quotation
Mod_gzip_item_exclude file ". css102sina>double_quotation

1.3. File Caching
This approach is usually for CGI programs such as PHP and Perl, because they have a common feature of not returning the results to the user immediately after a user's request, but explaining the execution results back to the customer after the interpreter has been interpreted, often involving access to the database. As a matter of fact, when two users visit the same page, the system will operate on two requests, but in reality the two operations may be identical, which adds to the burden of the system. So the usual solution is to open up a space in the system memory, when a user accesses the page for the first time, the execution results are stored in that memory, and when a user accesses the page again, the system calls the page directly from memory without having to perform a new interpretation, which is called caching. The current popular cache management program is Zend Technologies Company's Zend Cache.
2. Execute system external Command
PHP as a server-side scripting language, like writing simple, or complex dynamic Web pages such tasks, it is fully competent. But things are not always the case, sometimes in order to implement a function, you have to rely on the operating system of external programs (or called commands), so you can do more with less.
Calling an external command in PHP can be implemented in three ways as follows:
2.1. Specialized functions provided in PHP
PHP provides a total of 3 functions for executing external commands: System (), exec (), PassThru ().
System ()
Prototype: string system (String command [, int return_var])
The system () function is similar in other languages, it executes a given command, outputs, and returns results. The second parameter is optional and is used to get the status code after the command is executed.
Example:
System ("/usr/local/bin/webalizer/webalizer");
EXEC ()
Prototype: string exec (String command [, string array [, int return_var]])
The exec () function is similar to system () and executes the given command without outputting the result, but instead returns the last line of the result. Although it returns only the last line of the command result, the complete result can be obtained with the second parameter array, by appending the result line by row to the end of the array. So if the array is not empty, it's best to use unset () to clear it before calling. You can use the third parameter to obtain the status code of the command execution only if you specify the second parameter.
Example:
Copy Code code as follows:

EXEC ("/bin/ls-l");
EXEC ("/bin/ls-l", $res);
EXEC ("/bin/ls-l", $res, $RC);

PassThru ()
Prototype: void PassThru (String command [, int return_var])
PassThru () invokes only the command and does not return any results, but outputs the command's running results directly to the standard output device. So the PassThru () function is often used to invoke programs such as the Pbmplus (a tool that processes images under UNIX, outputting the stream of binary raw images). Likewise it can get the status code of the command execution.
Example:
Copy Code code as follows:

Header ("Content-type:image/gif");
PassThru ("./ppmtogif hunte.ppm");

2.2. Open a process with the Popen () function
The above method simply executes the command, but cannot interact with the command. But there are times when you have to enter something into the command, such as adding a Linux system user to call Su to change the current user to root, and the SU command must enter the root password on the command line. In this case, it is obviously not possible to use the method mentioned above.
The Popen () function opens a process pipeline to execute the given command, returning a file handle. Now that you are returning a file handle, you can read and write to it. In PHP3, this handle can only be done in a single mode of operation, either written or read; Starting with PHP4, you can read and write at the same time. Unless the handle is open in a pattern (read or write), you must call the Pclose () function to close it.
Example 1
$FP =popen ("/bin/ls-l", "R");
Example 2
Copy Code code as follows:

/* How to add a system user in PHP
Here's a routine that adds a user named James,
The root password is verygood. For reference only
*/
$sucommand = "Su--login root--command";
$useradd = "Useradd";
$ROOTPASSWD = "Verygood";
$user = "James";
$user _add = sprintf ("%s"%s "", $sucommand, $useradd, $user);
$fp = @popen ($user _add, "w");
@fputs ($fp, $ROOTPASSWD);
@pclose ($FP);

3. Develop a good program style
In many cases, the most valuable feature of PHP may be that its weakest link is its grammatical looseness. PHP can be used so widely because it allows many inexperienced web developers to build powerful applications without having to think too much about planning, consistency, and documentation. Unfortunately, it is the above characteristics, a lot of PHP source code is very bloated, it is difficult to read or even maintenance. An important factor in determining the maintainability of your code is the format and annotations of your code. All code for a project should be organized in a way that is always in the form. The following is a description of how to develop a good program code style in a PHP program.
3.1. Indent
All the code for the developer should be written in a completely indented way. This is the most basic measure to improve the readability of your code. Even if you don't annotate your code, indenting can be a great help for other people to read your code.
3.2. Add notes
It's a good habit to add annotations when you are programming. PHP allows comments to be added to the page code, with the same annotation method as the C language annotation syntax, which can be annotated in the script. You can use "* *" and "* *" to annotate a passage. The double slash "//" can be used as an annotation character.
3.3. Control structure
This depends to a large extent on personal taste. I can still see a lot of control structure code with no branching statements causing very poor readability, such as??? When you use an if statement without branching, not only is the readability worse, but when someone else modifies your program, it can cause a lot of bugs. Take a look at the following example:
A bad example:
if ($a = = 1) echo ' A is equal to 1 ';
This is very difficult to identify. It works, but no one else appreciates the code except you. Examples of improvements are:
if ($a = = 1)
Echo ' A was equal to 1 ';
Now at least this code can be read, but still not very good maintainability. What if I want an additional event to occur when $a==1, or do I need to add a branch? If later programmers forget to add braces or else keywords, bugs will appear in the program.
The perfect example
Copy Code code as follows:

if ($a = = 1) && ($b ==2)) {
Echo ' A was equal to 1 '; It's easy to add other code
} elseif (($a = = 1) && ($b ==3)) {//Other actions
}

Notice the spaces behind the IF and ElseIf, this distinguishes this statement from the function call, and even though there are no statements in the ElseIf execution segment, only annotations, seemingly superfluous, give very handy hints to programmers who later maintain the program, and are very useful for adding functionality.
3.4. Use Include to achieve the function of modularization
You can store commonly used functional functions in a PHP file, and in other PHP pages to use the function, include the function of the PHP file included in the call function of the PHP file. You can use the Include function. The specific syntax is:
Include ($FileName);
When used, you should note:
1, should avoid self contained, that is, File1 contains File1, when there are included statements in multiple files, you should avoid indirect self-contained, that is, loop contains, such as File1 contains File2,file2 contains File3,file3.
2, the included scripting language type must be a PHP language type or a script statement segment.

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.