Home >Backend Development >PHP Tutorial >PHP technology development skills sharing_PHP tutorial

PHP technology development skills sharing_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:40:101230browse

1. Improve the operating efficiency of PHP
One of the advantages of PHP is its fast speed, which can be said to be sufficient for general website applications. However, if the site's traffic is high, bandwidth is narrow, or other factors cause performance bottlenecks on the server, you may have to think of other ways to further increase the speed of PHP.
1.1. Code optimization
1. Use i+=1 instead of i=i+1. It conforms to the habits of c/c++ and is highly efficient.
 2. Use PHP internal functions as much as possible. Before writing a function yourself, you should check the manual in detail to see if there are any related functions, otherwise it will be a thankless task.
3. If you can use single-quoted strings, try to use single-quoted strings. Single quoted strings are more efficient than double quoted strings.
4. Use foreach instead of while to traverse the array. When traversing the array, the efficiency of foreach is significantly higher than that of the while loop, and there is no need to call the reset function. The two traversal methods are as follows:
Program 1:

Copy code The code is as follows:

 reset ($arr);
 while (list($key, $value) = each ($arr)) {
 echo "Key: $key; Value: $valuen";
 }

Program 2:
Copy code The code is as follows:

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

1.2. Compressed page
The HTTP1.1 protocol supports page compression and transmission, which means that the server sends a The page is compressed and sent to the client, where it is then decompressed and displayed to the client. There are two transmission methods on the server side. One is that the page has been compressed in advance. When transmitting, you only need to transmit the compressed page to the client. This is suitable for situations where there are many static web pages, but for most sites, dynamic pages are more Many, this method is not suitable, because many pages transmitted to the client actually do not exist. They are generated dynamically by the server upon receiving user requests from the client. Therefore, it is required that each dynamic page generated must be first generated before being transmitted to the client. Packed and compressed. From PHP version 4.0.4 onwards, you can add a line of configuration "output_handler = ob_gzhandler" in the php.ini file, so that each dynamically generated page will be compressed before being transmitted to the client, but according to the instructions on the PHP official site, This parameter cannot be used at the same time as the "zlib.output_compression = on" parameter, because it can easily cause PHP to work abnormally. In addition, it can only compress dynamically generated pages of the PHP program, but it will not work for a large number of static pages, especially image files. However, the mod_gzip module provides Apahe with the function of compressing static pages before transmitting them to the client. Its compression ratio can reach a maximum of 10, and generally can reach 3, which means that the transmission rate of the website has been increased by more than three times. . To use mod_gzip, you need to configure Apache accordingly. You need to add some parameters to the httpd.conf file:
Copy the code The code is as follows:

mod_gzip_on Yes (whether the 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 compressed file size) occupy memory)
mod_gzip_item_include file "..gif102SINA>DOUBLE_QUOTATION (Files ending in gif must be compressed and transmitted)
mod_gzip_item_include file ".txt102SINA>DOUBLE_QUOTATION
mod_gzip_item_include file ".html102S INA>DOUBLE_QUOTATION
 mod_gzip_item_exclude file ".css102SINA> DOUBLE_QUOTATION

1.3. File caching
This method is usually used for CGI programs such as PHP and PERL, because these programs have a common feature that they do not return the result to the user immediately after receiving the user's request, but The execution result is returned to the client after interpretation and execution by the interpreter, which usually involves database access. This will cause a problem. When two users access the same page, the system will operate on the two requests separately, but in fact the two operations may be exactly the same, which invisibly increases the burden on the system. Therefore, the usual solution is to open up a space in the system memory. When the user accesses the page for the first time, the execution result is stored in the memory. When the user accesses the page again, the system directly removes the page from the memory. Called out without reinterpretation and execution, this memory space is called cache. A currently popular cache management program is Zend Technologies' Zend Cache.
2. Execute external system commands
As a server-side scripting language, PHP is fully capable of tasks such as writing simple or complex dynamic web pages. But this is not always the case. Sometimes in order to implement a certain function, you must resort to external programs (or commands) of the operating system, so that you can get twice the result with half the effort.
To call external commands in PHP, you can use the following three methods:
2.1. Use the special functions provided by PHP
PHP provides a total of 3 special functions for executing external commands: system() , exec(), passthru().
System()
Prototype: string system (string command [, int return_var])
The system() function is similar to that in other languages. It executes the given command, outputs and returns the result. 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(). It also executes the given command, but does not output the result, but returns the last line of the result. Although it only returns the last line of the command result, using the second parameter array can get the complete result by appending the results line by line to the end of the array. So if the array is not empty, it is best to use unset() to clear it before calling it. Only when the second parameter is specified, the third parameter can be used to obtain the status code of command execution.
Example:
Copy code The code is 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() only calls the command and does not return any results, but outputs the command's running results directly to the standard output device as is. Therefore, the passthru() function is often used to call programs like pbmplus (a tool for processing images under Unix that outputs a binary stream of original images). It can also get the status code of command execution.
Example:
Copy code The code is as follows:

header("Content-type: image/gif");
passthru("./ppmtogif hunte.ppm");

2.2. Use the popen() function to open the process
The above method can only simply execute the command, but cannot be used with the command Interaction. But sometimes you must enter something into the command. For example, when adding a Linux system user, you need 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 pipe to execute the given command and returns a file handle. Since a file handle is returned, you can read and write to it. In PHP3, this kind of handle can only be used in a single operation mode, either writing or reading; starting from PHP4, it is possible to read and write at the same time. Unless the handle was opened in one mode (read or write), the pclose() function must be called to close it.
 Example 1
$fp=popen("/bin/ls -l", "r");
Example 2
Copy code The code is as follows:

/* How to add a system user in PHP
The following is a routine to add a user named james,
The root password is very good. For reference only
 */
 $sucommand = "su --login root --command";
 $useradd = "useradd ";
 $rootpasswd = "verygood";
 $user = "james";
$user_add = sprintf("%s "%s %s"",$sucommand,$useradd,$user);
$fp = @popen($user_add,"w") ;
 @fputs($fp,$rootpasswd);
 @pclose($fp);

3. Develop a good programming style
In many cases, the most valuable feature of PHP may also be its weakest link, which is its loose syntax. PHP is so widely used because it enables many inexperienced web developers to create powerful applications without having to worry too much about planning, consistency, and documentation. Unfortunately, due to the above characteristics, many PHP source codes are bloated, difficult to read or even impossible to maintain. An important factor in determining code maintainability is the format and comments of the code. All code for a project should be organized in a coherent manner. The following describes how to develop a good coding style in PHP programs.
3.1. Indentation
All code written by developers should be written exactly in the indented manner. This is the most basic measure to improve code readability. Even if you don't comment your code, indentation can be a huge help in making your code understandable to others.
 3.2. Add comments
It is a good habit to add comments when programming. PHP allows adding comments in the page code. The specific comment method is the same as the C language comment syntax. Comments can be added in the script. You can use "/*" and "*/" to comment out a paragraph. Double slashes "//" can be used as comment characters.
 3.3. Control structure
 This largely depends on personal taste. I can still see a lot of control structure code without branch statements, resulting in very poor readability. For example, when you use IF statements without branches, not only does the readability become worse, but when other people modify your program, It will also cause a lot of bugs. Look at the following example:
Bad example:
if ($a == 1) echo 'A was equal to 1';
This is very difficult to read. It will work, but no one will appreciate it except you. An improved example:
if ($a == 1)
echo 'A was equal to 1';
Now at least this code can be read, but it is still not very maintainable. . What if I want an additional event to occur when $a==1, or need to add a branch? If later programmers forget to add braces or else keywords, bugs will appear in the program.
Perfect example
Copy code The code is as follows:

if (($a == 1) && ($ b==2)) {
  echo 'A was equal to 1'; //It is easy to add other codes
 } elseif (($a == 1) && ($b==3)) { //Other operations
}

Please note the space after if and elseif, which will distinguish this statement from a function call. In addition, although in the execution section of elseif There are no statements, only comments. It seems redundant on the surface, but it gives very convenient tips to programmers who will maintain the program in the future, and is very helpful for adding functions.
 3.4. Use Include to realize function modularization
You can store commonly used functions in a PHP file. When you want to use the functions in other PHP pages, include the PHP file containing the function in the calling function. PHP file. At this time, you can use the Include function. The specific syntax is:
include($FileName);
When using it, you should pay attention to:
1. Self-containment should be avoided, that is, File1 contains File1; when there are include statements in multiple files, indirect self-containment should be avoided. Inclusion is circular inclusion, for example, File1 contains File2, File2 contains File3, and File3 contains File1.
 2. The type of the included script language must be a PHP language type or a script statement segment.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321463.htmlTechArticle1. Improve the operating efficiency of PHP. One of the advantages of PHP is that it is very fast. For general website applications, it can Saying yes is enough. However, if the site has high traffic, narrow bandwidth, or other...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn