Improve php code quality.

Source: Internet
Author: User
Tags closing tag

1. Do not use relative paths
We often see:
Require_once ('../lib/some_class.php ');
This method has many disadvantages:
It first looks for the specified php inclusion path and then finds the current directory.
Therefore, excessive paths are checked.
If the script is included by another script, its basic directory is changed to the directory where another script is located.
Another problem is that when a scheduled task runs the script, its parent directory may not be a working directory.
Therefore, the best choice is to use the absolute path:
Define ('root', '/var/www/project /');
Require_once (ROOT. '.../lib/some_class.php ');
// Rest of the code
We have defined an absolute path, and the value has been written to death. We can also improve it. The path/var/www/project may also change, so should we change it every time? No, we can use the _ FILE _ constant, for example:
// Suppose your script is/var/www/project/index. php
// Then _ FILE _ will always have that full path.
Define ('root', pathinfo (_ FILE __, PATHINFO_DIRNAME ));
Require_once (ROOT. '.../lib/some_class.php ');
// Rest of the code
Now, no matter which directory you move to, such as moving to an internet server, the code can run correctly without any changes.
2. Do not directly use require, include, include_once, required_once
You can introduce multiple files in the script header, such as class libraries, tool files, and helper functions. For example:
Require_once ('lib/Database. php ');
Require_once ('lib/Mail. php ');
Require_once ('helpers/utitlity_functions.php ');
This usage is quite primitive. It should be more flexible. A helper function should be compiled to include files. For example:
Function load_class ($ class_name)
{
// Path to the class file
$ Path = ROOT. '/lib/'. $ class_name. '. php ');
Require_once ($ path );
}
Load_class ('database ');
Load_class ('mail ');
Is there anything different? The code is more readable.
You can extend the function as needed, for example:
Function load_class ($ class_name)
{
// Path to the class file
$ Path = ROOT. '/lib/'. $ class_name. '. php ');
If (file_exists ($ path ))
{
Require_once ($ path );
}
}
You can also do more:
Search for multiple directories for the same file
It is easy to change the directory where class files are stored, without having to modify them one by one throughout the Code.
You can use similar functions to load files, such as html content.
3. Retain the debugging code for the Application
In the development environment, we print database query statements and store problematic variable values. Once the problem is solved, we comment or delete them. However, it is better to retain the debugging code.
In the development environment, you can:
Define ('Environment ', 'Development ');
If (! $ Db-> query ($ query)
{
If (ENVIRONMENT = 'development ')
{
Echo "$ query failed ";
}
Else
{
Echo "Database error. Please contact administrator ";
}
}
On the server, you can:
Define ('Environment ', 'production ');
If (! $ Db-> query ($ query)
{
If (ENVIRONMENT = 'development ')
{
Echo "$ query failed ";
}
Else
{
Echo "Database error. Please contact administrator ";
}
}
4. execute commands using cross-platform Functions
System, exec, passthru, and shell_exec functions can be used to execute system commands. every behavior has a slight difference. the problem is that some functions may be selectively disabled in the shared host. most new users tend to check which function is available at first, but use it again.
A better solution is to block functions into a cross-platform function.
/**
Method to execute a command in the terminal
Uses:
1. system
2. passthru
3. exec
4. shell_exec
*/
Function terminal ($ command)
{
// System
If (function_exists ('system '))
{
Ob_start ();
System ($ command, $ return_var );
$ Output = ob_get_contents ();
Ob_end_clean ();
}
// Passthru
Else if (function_exists ('passthru '))
{
Ob_start ();
Passthru ($ command, $ return_var );
$ Output = ob_get_contents ();
Ob_end_clean ();
}
// Exec
Else if (function_exists ('exec '))
{
Exec ($ command, $ output, $ return_var );
$ Output = implode ("\ n", $ output );
}
// Shell_exec
Else if (function_exists ('Shell _ exec '))
{
$ Output = shell_exec ($ command );
}
Else
{
$ Output = 'COMMAND execution not possible on this system ';
$ Return_var = 1;
}
Return array ('output' => $ output, 'status' => $ return_var );
}
Terminal ('LS ');
The above function will run shell commands, as long as there is a system function available, which maintains code consistency.
5. Flexible function writing
Function add_to_cart ($ item_id, $ qty)
{
$ _ SESSION ['cart'] ['item _ id'] = $ qty;
}
Add_to_cart ('iphone3', 2 );
Use the above function to add a single project. When adding an item list, do you want to create another function? No, as long as you pay attention to different types of parameters, it will be more flexible. For example:
Function add_to_cart ($ item_id, $ qty)
{
If (! Is_array ($ item_id ))
{
$ _ SESSION ['cart'] ['item _ id'] = $ qty;
}
Else
{
Foreach ($ item_id as $ I _id => $ qty)
{
$ _ SESSION ['cart'] ['I _ id'] = $ qty;
}
}
}
Add_to_cart ('iphone3', 2 );
Add_to_cart (array ('iphone3' => 2, 'ipad' => 5 ));
Now, the same function can process different types of input parameters. You can refer to the above example to reconstruct your multiple code to make it smarter.
6. Intentionally ignore php to close the tag
I 'd like to know why this is not mentioned in so many blog articles on php suggestions.
<? Php
Echo "Hello ";
// Now dont close this tag
This will save you a lot of time. Let's take an example:
A super_class.php File
<? Php
Class super_class
{
Function super_function ()
{
// Super code
}
}
?>
// Super extra character after the closing tag
Index. php
Require_once ('super _ class. php ');
// Echo an image or pdf, or set the cookies or session data
In this way, you will get a Headers already send error. Why? Because "super extra character" has been output. Now you have to start debugging. This will take a lot of time to find the super extra location.
Therefore, develop the habit of omitting the close character:
<? Php
Class super_class
{
Function super_function ()
{
// Super code
}
}
// No closing tag
This will be better.
7. Collect all input in a certain place and output it to the browser at a time
This is called the output buffer. Assume that you have output content in different functions:
Function print_header ()
{
Echo "<div id = 'header'> Site Log and Login links </div> ";
}
Function print_footer ()
{
Echo "<div id = 'footer '> Site was made by me </div> ";
}
Print_header ();
For ($ I = 0; I I <100; $ I ++)
{
Echo "I is: $ I <br/> ';
}
Print_footer ();
Instead, collect the output in a specific place. You can store the output in the local variables of the function, or use ob_start and ob_end_clean:
Function print_header ()
{
$ O = "<div id = 'header'> Site Log and Login links </div> ";
Return $ o;
}
Function print_footer ()
{
$ O = "<div id = 'footer '> Site was made by me </div> ";
Return $ o;
}
Echo print_header ();
For ($ I = 0; I I <100; $ I ++)
{
Echo "I is: $ I <br/> ';
}
Echo print_footer ();
Why is output buffer required:
> You can change the output before sending it to the browser. For example, the str_replaces function may be preg_replaces or add some monitoring/debugging html content.
> Php processing is terrible at the same time when the output is sent to the browser. You should have seen an error message in the sidebar or in the middle of some sites. Do you know why? Because the processing and output are mixed.
8. Send the correct mime type header information, if the output is not html content.
Output some xml.
$ Xml = '<? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> ';
$ Xml = "<response>
<Code> 0 </code>
</Response> ";
// Send xml data
Echo $ xml;
Work well, but some improvements are needed.
$ Xml = '<? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> ';
$ Xml = "<response>
<Code> 0 </code>
</Response> ";
// Send xml data
Header ("content-type: text/xml ");
Echo $ xml;
Note the header line. This line tells the browser to send xml content, so the browser can handle it correctly. Many javascript libraries also rely on header information.
Similar to javascript, css, jpg image, and png image:
JavaScript
Header ("content-type: application/x-javascript ");
Echo "var a = 10 ";
CSS
Header ("content-type: text/css ");
Echo "# div id {background: #000 ;}";
9. Set correct character encoding for mysql connections
I have encountered unicode/UTF-8 encoding in the mysql table, and phpadmin can be correctly displayed, but garbled characters may occur when you get the content and output it on the page. the problem lies in the character encoding of mysql connections.
// Attempt to connect to database
$ C = mysqli_connect ($ this-> host, $ this-> username, $ this-> password );
// Check connection validity
If (! $ C)
{
Die ("cocould not connect to the database host: <br/>". mysqli_connect_error ());
}
// Set the character set of the connection
If (! Mysqli_set_charset ($ c, 'utf8 '))
{
Die ('mysqli _ set_charset () failed ');
}
Once you connect to the database, it is best to set the connected characterset. If your application must support multiple languages, this is required.
10. Use htmlentities to set correct encoding options
Php5.4, character encoding is the default ISO-8859-1, can not directly output such as â.
$ Value = htmlentities ($ this-> value, ENT_QUOTES, CHARSET );
After php5.4, the default encoding is UTF-8, which will solve a lot of problems. But if your application is multilingual, still pay attention to coding problems ,.
11. Do not use gzip to compress the output in the application for apache to process
Have you considered using ob_gzhandler? Don't do that. It's meaningless. php should only be used to write applications. You shouldn't worry about data transmission optimization for servers and browsers.
Use the mod_gzip/mod_deflate module of apache to compress the content.
12. Use json_encode to output dynamic javascript content
Php is often used to output dynamic javascript content:
$ Images = array (
'Myself.png ', 'dsds.png', 'colleagues.png'
);
$ Js_code = '';
Foreach ($ images as $ image)
{
$ Js_code. = "'$ image ',";
}
$ Js_code = 'var images = ['. $ js_code.']; ';
Echo $ js_code;
// Output is var images = require 'myself.png ', 'dsds.png', 'colleagues.png ',];
To be smarter, use json_encode:
$ Images = array (
'Myself.png ', 'dsds.png', 'colleagues.png'
);
$ Js_code = 'var images = '. json_encode ($ images );
Echo $ js_code;
// Output is: var images = ["myself.png", "friends.png", "colleagues.png"]
Elegant?
13. Check the directory write permission before writing a file.
Make sure that the directory is writable before writing or saving the file. If not, output the error message. this will save you a lot of debugging time. in linux, permissions must be handled. Improper directory permissions may cause many problems, and files may not be readable.
Make sure that your application is smart enough to output some important information.
$ Contents = "All the content ";
$ File_path = "/var/www/project/content.txt ";
File_put_contents ($ file_path, $ contents );
This is basically correct. But there are some indirect problems. file_put_contents may fail for several reasons:
> The parent directory does not exist.
> The directory exists but cannot be written.
> Is the file written and locked?
Therefore, it is better to make a clear check before writing the file.
$ Contents = "All the content ";
$ Dir = '/var/www/project ';
$ File_path = $ dir. "/content.txt ";
If (is_writable ($ dir ))
{
File_put_contents ($ file_path, $ contents );
}
Else
{
Die ("Directory $ dir is not writable, or does not exist. Please check ");
}
After doing so, you will get a clear information about where the file is written and why it fails.
14. Change the file permissions created by the application.
In linux, permission issues may waste a lot of time. from now on, whenever you create some files, make sure to use chmod to set the correct permissions. otherwise, the file may be first created by the "php" user, but when you log on to work with another user, the system will refuse to access or open the file, and you have to struggle to obtain the root permission, change file permissions, etc.
// Read and write for owner, read for everybody else
Chmod ("/somedir/somefile", 0644 );
// Everything for owner, read and execute for others
Chmod ("/somedir/somefile", 0755 );
15. Do not rely on the value of the submit button to check the form submission Behavior
If ($ _ POST ['submit '] = 'save ')
{
// Save the things
}
Most of the above situations are correct, except that the application is multilingual. 'save' may represent other meanings. How do you differentiate them? Therefore, do not rely on the value of the submit button.
If ($ _ SERVER ['request _ method'] = 'post' and isset ($ _ POST ['submit '])
{
// Save the things
}
Now you are freed from the value of the submit button.
16. Define static variables for variables with the same value in the function.
// Delay for some time
Function delay ()
{
$ Sync_delay = get_option ('sync _ delay ');
Echo "<br/> Delaying for $ sync_delay seconds ...";
Sleep ($ sync_delay );
Echo "Done <br/> ";
}
Replace with static variables:
// Delay for some time
Function delay ()
{
Static $ sync_delay = null;
If ($ sync_delay = null)
{
$ Sync_delay = get_option ('sync _ delay ');
}
Echo "<br/> Delaying for $ sync_delay seconds ...";
Sleep ($ sync_delay );
Echo "Done <br/> ";
}
17. Do not directly use the $ _ SESSION variable
Some simple examples:
$ _ SESSION ['username'] = $ username;
$ Username = $ _ SESSION ['username'];
This may cause some problems. if multiple applications are running in the same domain name, the session variable may conflict. two different applications may use the same session key. for example, a front-end portal and a background management system use the same domain name.
From now on, use the key related to the application and a packaging function:
Define ('app _ id', 'abc _ corp_ecommerce ');
// Function to get a session variable
Function session_get ($ key)
{
$ K = APP_ID. '.'. $ key;
If (isset ($ _ SESSION [$ k])
{
Return $ _ SESSION [$ k];
}
Return false;
}
// Function set the session variable
Function session_set ($ key, $ value)
{
$ K = APP_ID. '.'. $ key;
$ _ SESSION [$ k] = $ value;
Return true;
}
18. encapsulate tool functions into classes
Assume that you have defined many tool functions in a file:
Function utility_a ()
{
// This function does a utility thing like string processing
}
Function utility_ B ()
{
// This function does nother utility thing like database processing
}
Function utility_c ()
{
// This function is...
}
The usage of these functions is scattered throughout the application. You may want to encapsulate them into a class:
Class Utility
{
Public static function utility_a ()
{
}
Public static function utility_ B ()
{
}
Public static function utility_c ()
{
}
}
// And call them
$ A = Utility: utility_a ();
$ B = Utility: utility_ B ();
The obvious advantage is that if a function with the same name is built in php, conflicts can be avoided.
Another idea is that you can maintain multiple versions for the same class in the same application without causing conflict. This is the basic benefit of encapsulation and does not exist.
19. Bunch of silly tips
> Replace print with echo
> Replace preg_replace with str_replace unless you absolutely need
> Do not use the short tag
> Replace double quotation marks with single quotes for a simple string
> Use exit AFTER head redirection
> Do not call a function in a loop
> Isset is faster than strlen
> The first example is the formatting code.
> Do not delete the parentheses of the loop or if-else.
Do not write code like this:
If ($ a = true) $ a_count ++;
This is definitely WASTE.
Written:
If ($ a = true)
{
$ A_count ++;
}
Do not try to omit some syntax to shorten the code, but make your logic brief.
> Use a text editor with highlighted syntax to reduce errors.
20. Use array_map to quickly process Arrays
For example, if you want to trim all elements in the array, new users may:
Foreach ($ arr as $ c => $ v)
{
$ Arr [$ c] = trim ($ v );
}
However, using array_map is simpler:
$ Arr = array_map ('trim', $ arr );
This will apply to call trim for every element of the $ arr array. Another similar function is array_walk. Please refer to the document for more tips.
21. Use php filter to verify data
You must have used regular expressions to verify emails, IP addresses, etc. Yes, everyone is using this. Now, we want to make different attempts, called filters.
Php's filter Extension provides a simple way to verify and check input.
22. Force type check
$ Amount = intval ($ _ GET ['amount ']);
$ Rate = (int) $ _ GET ['rate'];
This is a good habit.
23. If necessary, use profiler such as xdebug
If you use php to develop large applications, php takes a lot of computations, and the speed will be a very important indicator. Using profile to help optimize code can be used.
Xdebug and webgrid.
24. handle large arrays with caution
You must be careful when handling large arrays and strings. A common Error is that Memory overflow occurs due to an array copy and Fatal Error of Memory size is thrown:
$ Db_records_in_array_format; // This is a big array holding 1000 rows from a table each having 20 columns, every row is atleast 100 bytes, so total 1000*20*100 = 2 MB
$ Cc = $ db_records_in_array_format; // 2 MB more
Some_function ($ cc); // Another 2 MB?
This is often done when you import or export csv files.
Do not think that the above Code will often cause the script to crash due to memory restrictions. It is okay for small variables, but it must be avoided when processing large arrays.
Make sure that it is passed by reference or stored in class variables:
$ A = get_large_array ();
Pass_to_function (& $ );
After doing so, pass the variable reference (instead of copying the array) to the function. view the document.
Class
{
Function first ()
{
$ This-> a = get_large_array ();
$ This-> pass_to_function ();
}
Function pass_to_function ()
{
// Process $ this->
}
}
Unset them as soon as possible to release the memory and reduce the script burden.
25. Use a single database to connect to the database
Make sure that all scripts use a single database connection from the beginning. Open the connection correctly at the beginning, use it until the end, and close it. Do not open the connection in the function as follows:
Function add_to_cart ()
{
$ Db = new Database ();
$ Db-> query ("insert into cart .....");
}
Function empty_cart ()
{
$ Db = new Database ();
$ Db-> query ("delete from cart .....");
}
Using multiple connections is too bad. They will slow down the application because it takes time and memory to create a connection.
The Singleton mode is used in specific cases, such as database connection.
26. Avoid writing SQL directly and abstract it
Too many of the following statements have been written:
$ Query = "insert into users (name, email, address, phone) VALUES ('$ name',' $ email ',' $ address ',' $ phone ')";
$ Db-> query ($ query); // call to mysqli_query ()
This is not a strong solution. It has some disadvantages:
> Manually escape values every time
> Verify that the query is correct.
> Query errors take a long time to identify (unless if-else is used for each check)
> It is difficult to maintain complex queries.
Therefore, function encapsulation is used:
Function insert_record ($ table_name, $ data)
{
Foreach ($ data as $ key => $ value)
{
// Mysqli_real_escape_string
$ Data [$ key] = $ db-> mres ($ value );
}
$ Fields = implode (',', array_keys ($ data ));
$ Values = "'". implode ("', '", array_values ($ data ))."'";
// Final query
$ Query = "insert into {$ table} ($ fields) VALUES ($ values )";
Return $ db-> query ($ query );
}
$ Data = array ('name' => $ name, 'email '=> $ email, 'address' => $ address, 'phone' => $ phone );
Insert_record ('users', $ data );
Have you seen it? This will make it easier to read and expand. The record_data function carefully handles the escape.
The biggest advantage is that the data is preprocessed into an array, and any syntax errors will be captured.
This function should be defined in a database class. You can call it like $ db-> insert_record.
Read this article to see how to make it easier for you to process the database.
You can also compile the update, select, and delete methods.
27. cache the content generated by the database to a static file.
If all contents are obtained from the database, they should be cached. once generated, they are saved in temporary files. the next time you request this page, you can directly retrieve it from the cache without querying the database.
Benefits:
> Saving php processing time and faster execution
> Less database queries mean less mysql connection overhead
28. Save the session in the database
The file-based session policy has many restrictions. the file-based session cannot be extended to the cluster because the session is stored on a single server. however, the database can be accessed by multiple servers to solve the problem.
Saving session data in the database has the following benefits:
> Solve the problem of repeated username logon. The same username cannot be logged on at the same time in two locations.
> More prepared online user statuses can be queried.
29. Avoid using global variables
> Use defines/constants
> Use functions to obtain values
> Use the class and access it through $ this
30. Use the base tag in the head
Have you heard of it? See the following:
<Head>
<Base href = "http://www.domain.com/store/">
</Head>
<Body>

</Body>
</Html>
Base labels are very useful. Suppose your application is divided into several sub-directories, which must contain the same navigation menu.
Www.domain.com/store/home.php
Www.domain.com/store/products/ipad.php
On the homepage, you can write:
<A href = "home. php"> Home </a>
<A href = "products/ipad. php"> Ipad </a>
But on your ipad. php, you have to write:
<A href = "../home. php"> Home </a>
<A href = "ipad. php"> Ipad </a>
Because the directories are different, there are so many different versions of navigation menus to be maintained, which is very bad.
Therefore, use the base tag.
<Head>
<Base href = "http://www.domain.com/store/">
</Head>
<Body>
<A href = "home. php"> Home </a>
<A href = "products/ipad. php"> Ipad </a>
</Body>
</Html>
Now, this code is stored in the directory files of the application and the behavior is consistent.
31. Never set error_reporting to 0
Disable the non-Phase Error Report. E_FATAL error is very important.
Ini_set ('display _ errors ', 1 );
Error_reporting (~ E_WARNING &~ E_NOTICE &~ E_STRICT );
32. Pay attention to the Platform Architecture
Integer length is different in the 32-bit and 64-bit architectures. Therefore, some functions such as strtotime may behave differently.
In a 64-bit machine, you will see the following output.
$ Php-
Interactive shell
Php> echo strtotime ("0000-00-00 00:00:00 ");
-62170005200
Php> echo strtotime ('2017-01-30 ');
-30607739600
Php> echo strtotime ('2017-01-30 ');
4104930600
But in 32-bit machines, they will be bool (false). check here for more information.
33. Do not rely too much on set_time_limit
If you want to limit the minimum time, you can use the following script:
Set_time_limit (30 );
// Rest of the code
Sit back and relax? Note that any external execution, such as system calls, socket operations, and database operations, is not under the control of set_time_limits.
Therefore, even if the database spends a lot of time querying, the script will not stop running, depending on the situation.
34. Use extension Library
Some examples:
> MPDF -- generate pdf documents through html
> PHPExcel -- Read and Write excel
> PhpMailer -- easily process and send emails containing nearby emails
> PChart -- generate a report using php
Use open-source libraries to complete complex tasks, such as generating pdf, ms-excel files, and reports.
35. Use the MVC Framework
It is time to use MVC frameworks like codeigniter. MVC frameworks do not force you to write object-oriented code. They only separate php code from html.
> Clearly differentiate php and html code. It is helpful for team collaboration. Designers and programmers can work at the same time.
> Object-oriented functions make it easier for you to maintain
> The built-in functions have completed a lot of work and you do not need to write them again.
> Development of large applications is required.
> Many suggestions, tips, and hack have been implemented by the framework.
36. Always look at phpbench
Phpbench provides benchmark test results for some basic php operations. It shows how small syntax changes lead to huge differences.
Check the comments of the php site, ask IRC if you have any questions, read the open source code frequently, and use Linux for development.
OSCHINA Original translation

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.