50 Practical tips for high quality PHP code (top) _php tips

Source: Internet
Author: User
Tags chmod closing tag learn php parent directory sleep trim file permissions

50 of High-quality PHP code practical skills, I hope you like.

1. Do not use relative paths
you will often see:

Require_once ('.. /.. /lib/some_class.php ');

This approach has many drawbacks: it first finds the specified PHP include path, and then finds the current directory. Therefore, too many paths are checked. If the script is contained by a script in another directory, its base directory becomes the directory where another script resides.

Another problem is that when a timed task runs the script, its parent directory may not be a working directory. So the best option is to use an absolute path:

View Sourceprint?
 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 is written dead. We can also improve it. Path/var/www/project may also change, so do we have to change it every time? No, we can use __file__ constants, such as:

Suppose your script is/var/www/project/index.php
 //then __file__ 'll 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 extranet server, the code can run correctly without changing it.

2. Do not use require directly, include, Include_once, required_once
you can introduce multiple files, such as class libraries, tool files, and helper functions, in the script header, such as:

Require_once (' lib/database.php ');
 Require_once (' lib/mail.php ');
 Require_once (' helpers/utitlity_functions.php ');

This usage is quite primitive. should be more flexible. You should write an assistant function containing the file. 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 on demand, such as:

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 do more: find multiple directories for the same file. It's easy to change the directory where the class files are placed, without having to make one by one changes throughout the code. You can use similar functions to load files, such as HTML content.

3. Keep Debug code for application
in the development environment, we print the database query statements, dump the variable values of the problem, and once the problem is resolved, we annotate or delete them. A better practice, however, is to keep the debug 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 ";
 }
 }

In 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. Use Cross-platform functions to execute commands
System, exec, PassThru, shell_exec these 4 functions can be used to execute systems commands. Every action has a slight difference. The problem is that when in a shared host, some functions may be selectively disabled. Most beginners tend to check which function is available at a time, but use it again. A better solution is to marshal the function into a cross-platform function.

/** 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 the shell command, as long as a system function is available, which keeps the code consistent.

5. Flexible writing functions

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 item. And when you add a list of items, do you want to create another function? No, just a little attention to the different types of parameters, you will be more flexible. Such as:

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 handle different types of input parameters. You can refactor your multiple code to make it smarter by referencing the example above.

6. Intentionally ignore PHP close tag
I'd like to know why so many blog posts about PHP recommendations do not mention this.

<?php
 echo "Hello";
 Now dont close this tag

This will save you a lot of time. Let's give 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 cookie or session data

In this way, you will get a Headers already send error. Why? Because "super extra character" has been exported. Now you have to start debugging. This will take a lot of time to find the location of Super extra. Therefore, develop the habit of omitting the closing character:

<?php
 class Super_class
 {
 function super_function ()
 {
 //super code
 }
 }
 //no closing Tag

It would be better.

7. Collect all input at one place, output to browser at a time
This is called the output buffer, if you have already output the content in a different function:

function Print_header ()
 {
 echo "<div id= ' header ' >site Log and Login links</div>";
 }
 function Print_footer ()
 {
 echo "<div id= ' footer ' >site is made by me</div>";
 }
 Print_header ();
 for ($i = 0; $i < $i + +)
 {
 echo ' I is: $i ';
 }
Print_footer ();

Alternative, where the output is collected centrally. You can store it in a local variable of a function, or you can use Ob_start and Ob_end_clean. As follows:

function Print_header ()
 {
 $o = "<div id= ' header ' >site Log and Login links</div>";
 return $o;
 }
function Print_footer ()
 {
 $o = "<div id= ' footer ' >site is made by me</div>";
 return $o;
 }
Echo Print_header ();
 for ($i = 0; $i < $i + +)
 {
 echo ' I is: $i ';
 }
 Echo Print_footer ();

Why output buffering is required:
>> can change the output before sending it to the browser. such as the Str_replaces function or may be preg_replaces or add some monitoring/debugging HTML content.
>> output to the browser while doing PHP processing is very bad. You should have seen an error message in the sidebar or in the middle of some sites. Do you know why it happened? Because 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 Header line. The line tells the browser to send the content of the XML type. So the browser can handle it correctly. Many JavaScript libraries also rely on header information.
Similar to JavaScript, CSS, jpg image, PNG image:

JavaScript
Header ("Content-type:application/x-javascript");
 echo "var a = ten";
 CSS
Header ("Content-type:text/css");
 echo "#div ID {background: #000;}";

9. Set the correct character encoding for the MySQL connection
have encountered in the MySQL table set unicode/utf-8 encoding, Phpadmin can also be displayed correctly, but when you get the content and output in the page, there will be garbled. Here's the problem with the character encoding of the MySQL connection.

Attempt to connect to database
 $c = Mysqli_connect ($this->host, $this->username, $this->password);
 Check Connection Validity
 if (! $c)
 {
 die ("Could not connect to the" database host: ". Mysqli_connect_error ());
 }
 Set the character set of the connection
if (!mysqli_set_charset ($c, ' UTF8 '))
 {
 die (' Mysqli_set_charse T () failed ');
 

Once the database is connected, it is best to set the characterset of the connection. If your application is to support multiple languages, it is necessary to do so.

10. Use Htmlentities to set the correct encoding options
before php5.4, the character's default encoding is iso-8859-1 and cannot be directly output such as Àâ.

$value = Htmlentities ($this->value, ent_quotes, CHARSET);

After php5.4, the default encoding is UTF-8, which will solve many problems. But if your application is multilingual, still pay attention to coding problems.

11. Do not use gzip compression output in the application, let Apache processing
have you considered using Ob_gzhandler? Don't do that. It doesn't make any sense. PHP applies only to write applications. You should not worry about server and browser data transfer optimization issues.
Use Apache's Mod_gzip/mod_deflate module to compress content.

12. Output dynamic JavaScript content using Json_encode
PHP is often used to output dynamic JavaScript content:

$images = Array (
 ' myself.png ', ' friends.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 = [' Myself.png ', ' friends.png ', ' colleagues.png ',];
  
Smarter approach, using Json_encode:
  
$images = Array (
 ' myself.png ', ' friends.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 directory Write permissions before writing files
before you write or save the file, make sure that the directory is writable, if not writable, and output error messages. This will save you a lot of debugging time. Linux system, the need to process permissions, directory permissions will cause a lot of problems, files may not read and so on.
Make sure your application is smart enough to output some important information.

$contents = "All content";
$file _path = "/var/www/project/content.txt";
 File_put_contents ($file _path, $contents);

This is generally true. But there are some indirect problems. File_put_contents may fail for several reasons:
>> Parent Directory does not exist
>> directory exists, but not writable
>> files are written and locked?
So it's better to make a clear check before writing a file.

$contents = "All content";
 $dir = '/var/www/project ';
 $file _path = $dir. "/content.txt";
 if (is_writable ($dir))
 {
 file_put_contents ($file _path, $contents);
 }
 else
 {
 die ("Directory $dir isn't writable, or does not exist.") Please check ");
 }

After doing so, you will get a clear message of where the file is written and why it failed.

14. Change file permissions created by application
in a Linux environment, permissions issues can waste you a lot of time. From now on, whenever you create some files, be sure to use chmod to set the correct permissions. Otherwise, the file may first be created by the "PHP" user, but you log in to work with other users, the system will deny access or open files, you have to struggle to get root permissions, change file permissions, and so on.

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 submit button values to check form submission behavior

if ($_post[' submit '] = = ' Save ')
 {
 //save the things
 }

Most of the above is true, except that the application is multilingual. ' Save ' may represent other meanings. How do you tell them apart? 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 a static variable for a variable that always has the same value within a function

Delay for some time
 function Delay ()
 {
 $sync _delay = get_option (' Sync_delay ');
 echo "Delaying for $sync _delay seconds ...";
 Sleep ($sync _delay);
 echo "Done";
 }

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 "Delaying for $sync _delay seconds ...";
 Sleep ($sync _delay);
 echo "Done";
 }

17. Do not use $_session variables directly
Some simple examples:

$_session[' username ' = $username;
 $username = $_session[' username '];

This can 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 using the same domain name. From now on, use the application-related key and a wrapper 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 a tool function into a class
If you define a lot of 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 use of these functions is dispersed throughout the application. You might want to encapsulate them in a class:

Class Utility
 {public
static function utility_a ()
{
} public
static function Utility_b (
 ) {
 }
public static function Utility_c ()
 {
 }
 }
//and call them as
 $a = utility::utility_a ();
 $b = Utility::utility_b ();

The obvious benefit is that if you have a function with the same name in PHP, you can avoid conflicts.
Another view is that you can maintain multiple versions of the same class in the same application without causing conflicts. This is the basic benefit of encapsulation, without it.

Bunch of Silly tips
>> use echo instead of print
>> use Str_replace instead of preg_replace unless you absolutely need
>> do not use short tag
>> simple strings replace double quotes with single quotes
Remember to use exit after >>head redirection
>> do not call functions in loops
>>isset faster than strlen.
>> formatting code in the beginning
>> do not delete loops or if-else parentheses
Do not write code like this:

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" >if ($a = = true) $a _count++;</span>

This is absolutely waste. Written:

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" >if ($a = = True)
 {
 $a _count++
 } </span>

Do not attempt to omit some syntax to shorten the code. But to keep your logic short.
>> use a text editor with the highlighted syntax. Highlighting syntax can make you less wrong.

20. Using Array_map to quickly process arrays
For example, you want to trim all the elements in an array. Novice May:

foreach ($arr as $c => $v)
 {
 $arr [$c] = Trim ($v);
 }

But using Array_map is simpler:

$arr = Array_map (' Trim ', $arr);

This applies to call trim for each element of the $arr array. Another similar function is Array_walk. Consult your documentation for more tips.

21. Validating Data with PHP filter
you must have used regular expressions to validate emails, IP addresses, and so on. Yes, everyone uses it that way. Now, we want to do a different try, called filter.
The PHP Filter extension provides a simple way to validate and check input.

22. Mandatory type checking

$amount = intval ($_get[' amount '));
$rate = (int) $_get[' rate '];

It's a good habit.

23. If necessary, use profiler such as Xdebug
If you use PHP to develop a large application, PHP takes on a lot of computing, and speed is an important indicator. Use profile to help optimize your code. You can use Xdebug and WebGrid.

24. Handle large arrays with care
For large arrays and strings, it must be handled with care. A common error occurs when an array copy causes a memory overflow and throws fatal error of Memory size information:

$db _records_in_array_format; This is a big array holding 1000 rows from a table each has a columns, every row is atleast-bytes, so total 10 * mb = 2MB
$cc = $db _records_in_array_format//2mb more
some_function ($CC);//another 2MB?

This is often done when you import or export a CSV file. Do not assume that the above code will often cause the script to crash due to memory limitations. Small variables are fine, but they must be avoided when dealing with large arrays.
Make sure that it is passed by reference or stored in a class variable:

$a = Get_large_array ();
 Pass_to_function (& $a);

After doing so, pass the variable reference to the function instead of the copy array. View the document.

Class A
 {
 function A ()
 {
 $this->a = Get_large_array ();
 $this->pass_to_function ();
 }
 function pass_to_function ()
 {
 //process $this->a
 }
 }

Unset them as soon as possible, so that the memory can be released, reduce the burden of the script.

25. Use a single database connection from beginning to end
Make sure that your scripts use a single database connection from beginning to end. Open the connection correctly at the beginning, use it until it ends, and close it at the end. 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 a bad thing, they slow down applications because it takes time and memory to create a connection. Specific cases use a single case pattern, such as a database connection.

This cheats is not very exciting, I believe that you must learn PHP program design help.

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.