More than 40 PHP skills useful to beginners (2)

Source: Internet
Author: User
More than 40 PHP skills useful to beginners (2)

11. do not make gzip output in your application. let apache do it.

Consider using ob_gzhandler? No, don't do this. It makes no sense. PHP should be used to write applications. Don't worry about how to optimize the data transmitted between the server and the browser in PHP.

Use apache mod_gzip/mod_deflate to compress the content through the. htaccess file.

12. use json_encode when echo javascript code from php

Sometimes some JavaScript code is dynamically generated from php.

$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' ,];

Be smart. 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"]

Isn't it neat?

13. check whether the directory is writable before writing any files.

Before writing or saving any files, check whether the directory is writable. if the directory is not writable, an error message will flash. This will save you a lot of "debugging" time. When you work in Linux, the permissions must be handled, and there are many permission problems, when the directory cannot be written, the file cannot be read.

Make sure that your applications are as intelligent as possible and report the most important information in the shortest time.

$contents = "All the content";$file_path = "/var/www/project/content.txt";file_put_contents($file_path , $contents);

This is completely correct. But there are some indirect problems. File_put_contents may fail for some reason:

Parent directory does not exist

Directory exists, but cannot be written

Is the locked file used for writing?

Therefore, it is best to clarify everything before writing a 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");}

By doing so, you can get the accurate information about the file writing failure and the failure.

14. change the permissions of the files created by the application.

When working in Linux, permission processing will waste a lot of time. Therefore, as long as your php application creates some files, you should modify their permissions to make sure they are "approachable" outside ". Otherwise, for example, if a file is created by a "php" user and you are a different user, the system will not allow you to access or open the file. then you must strive to obtain the root permission, change file permissions.

// Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755);

15. do not check the submit button value to check form submission

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

The above code is correct most of the time except when the application uses multiple languages. Then "Save" can be a lot of different things. So how do you compare them? Therefore, you cannot rely on the value of the submit button. Instead, use this:

if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ){    //Save the things}

Now you can get rid of the value of the submit button.

16. use static variables where the function always has the same value

//Delay for some timefunction delay(){    $sync_delay = get_option('sync_delay');    echo "
 Delaying for $sync_delay seconds...";    sleep($sync_delay);    echo "Done 
 ";}

Instead, use static variables:

//Delay for some timefunction 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 are:

$_SESSION['username'] = $username;$username = $_SESSION['username'];

But there is a problem. If you are running multiple applications in the same domain, session variables conflict. Two different applications may set the same key name in the session variable. For example, a front-end Portal and background management application with the same domain.

Therefore, use the wrap function to use the application-specific key:

define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){    $k = APP_ID . '.' . $key;    if(isset($_SESSION[$k]))    {        return $_SESSION[$k];    }    return false;}//Function set the session variablefunction session_set($key , $value){    $k = APP_ID . '.' . $key;    $_SESSION[$k] = $value;    return true;}

18. encapsulate practical helper functions into a class

Therefore, you must have a lot of practical 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 ...}

Use functions freely in applications. You may want to wrap them into a class as a static function:

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();

One obvious benefit you can get is that if php has built-in functions with similar names, the names will not conflict.

From another perspective, you can keep multiple versions of the same class in the same application without any conflict. This is because it is encapsulated.

19. some silly tricks

Use echo instead of print

Use str_replace instead of preg_replace unless you are sure you need it

Do not use short tags

Use single quotes instead of double quotes for simple strings

Remember to make an exit after the header is redirected

Do not place function calls in the for loop control line.

Isset is faster than strlen

Correct and consistent formatting of your code

Do not lose the parentheses of the loop or ifelse block.

Do not write such code:

if($a == true) $a_count++;

This is definitely a waste.

Write in this way

if($a == true){    $a_count++;}

Do not shorten your code by eating the syntax. But to make your logic shorter.

Use a text editor with code highlighting. Code highlighting helps reduce errors.

20. use array_map to quickly process arrays

For example, you need to trim all elements of an array. Newbie will do this:

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

But it can use array_map to become more neat:

$arr = array_map('trim' , $arr);

This applies to all elements of the trim array $ arr. Another similar function is array_walk.

21. Use a php filter to verify data

Do you use regular expressions to verify the equivalence of IP addresses such as emails? Yes, this is what everyone does. Now, let's try a different thing, that is, the filter.

The php filter extension provides a simple method to effectively verify or verify the value.

22. Force type check

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

This is a good habit.

23. use set_error_handler () to write Php errors to files

Set_error_handler () can be used to set custom error handling programs. It is a good idea to write some important errors in the file for logging.

24. handle large arrays with caution

A large array or string. if a variable stores something very large, be careful with it. A common error is a fatal error that creates a copy, consumes memory, and causes memory overflow:

$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 code is common when importing csv files or exporting tables to csv files.

As shown above, scripts may often crash due to memory restrictions. Small-scale variables do not cause problems, but must be avoided when processing large arrays.

Consider passing them by referencing or storing them in a class variable:

$a = get_large_array();pass_to_function(&$a);

In this way, the same variable (not its copy) will be used for this function.

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

Restore them as soon as possible so that the memory can be released and the rest of the script can be relaxed.

The following is a simple example of how to save memory by assigning values through reference.

 ';$b = $a;$b[0] = 'B';echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '
 ';$c = $a;$c[0] = 'B';echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '
 ';$d =& $a;$d[0] = 'B';echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '
 ';

The output on a typical php 5.4 Machine is:

Memory usage in MB : 18.08208Memory usage in MB after 1st copy : 27.930944Memory usage in MB after 2st copy : 37.779808Memory usage in MB after 3st copy (reference) : 37.779864

Therefore, we can see that the memory is saved in 3rd copies that are referenced by reference. Otherwise, the memory will be used more and more in all common replicas.

25. use a single database connection in the entire script

Make sure that you use a single database connection throughout the script. Open the connection from the beginning, use it to the end, 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 .....");}

It is not good to have multiple connections because each connection takes time to create and use more memory, leading to slow execution.

In special cases. For example, you can use the Singleton mode for database connection.

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.