Php tips: 50 practical skills for high-quality php code (part 1)

Source: Internet
Author: User
Tags closing tag learn php programming
Php tips: 50 practical skills for high-quality php code (I). I hope you will like it. I hope you will like the practical skills of 50 high-quality PHP codes.

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 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:

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 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: find 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.

 

This will save you a lot of time. let's take an example:
A super_class.php file

 //super extra character after the closing tagindex.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:

  

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 "Site Log and Login links"; } function print_footer() { echo "Site was made by me"; } print_header(); for($i = 0 ; $i < 100; $i++) { echo "I is : $i '; }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 = "Site Log and Login links"; return $o; }function print_footer() { $o = "Site was made by me"; return $o; }echo print_header(); for($i = 0 ; $i < 100; $i++) { echo "I is : $i '; } 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 = "0 ";//Send xml data echo $xml;

Work well, but some improvements are needed.

$xml = ''; $xml = "0 "; //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:

JavaScriptheader("content-type: application/x-javascript"); echo "var a = 10"; CSSheader("content-type: text/css"); echo "#p 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 ("Could not connect to the database host: ". mysqli_connect_error()); } //Set the character set of the connectionif(!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 ', '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 = require 'myself.png ', 'friends.png', 'colleagues.png ',]; a smarter way to use 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 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 "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 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 as $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. use profile to help optimize code. xdebug and webgrid can be used.

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 = 2MB$cc = $db_records_in_array_format; //2MB moresome_function($cc); //Another 2MB ?

This is often the case 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(&$a);

After doing so, pass the variable reference (instead of copying the array) to the function. view the document.

class A { function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a } }

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 ..

This secret is not very good, I believe it will be helpful for everyone to learn php programming.

Related articles:

Php tips: 50 practical tips for high-quality php code (part 1)

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.