30 PHP Best Practices for beginners (wilderness without lights) _php tips

Source: Internet
Author: User
Tags php code php framework php script sql injection netbeans
1, and PHP manuals become good friends
2, open the error Reporting
The error reporting is helpful in PHP development. You can find errors in your code that you didn't find before, because not all bugs are going to run the program. When the product is formally used, it is necessary to turn off the error report, or customers see a bunch of strange characters do not know what that means.
3, using the IDE
The IDE (Integrated development environment, integrated Development environments) is a useful tool for developers.
Wilderness here recommends the NetBeans IDE.
4. Try using a PHP framework
5. Learning Dry Methods
DRY represents Don ' t Repeat yourself, which is a valuable programming concept, no matter what language it is. Dry programming, as the name suggests, is to make sure you don't write extra code.
6. Use space to indent code to improve readability
7. "Tier" Your Code
Give your application layered, divided into different parts of the code for different components. This makes it easy for you to change your code in the future. such as the common MVC pattern.
8. Always use <?php?>
9. Use meaningful, consistent naming conventions
10. Notes, notes, notes
11. Install Mamp/wamp
12. Limit running time to your scripts
PHP scripts typically run for 30 seconds, and PHP throws a fatal error over that time.
13. Using OOP
14. Know the difference between double quotes and single quotes
15. Do not put phpinfo in the root directory of the website ()
16. Never trust your users
17. Encrypt Store password
Rebuttal:
Keep in mind, however, that MD5 hashes have long since been. They ' re absolutely more secure than no, but, with the use of a enormous "rainbow table," Hackers can cross reference you R Hash. To add even, consider adding a salt as. A Salt is basically an additional set of characters this you append to the user ' s string.
18. Use of Visual Database design tools
such as Dbdesigner and MySQL Workbench
19. Use Output buffer
Rebuttal:though not required, it's generally considered to is a good practice to go ahead and append the "Ob_end_flush" (); function as the bottom of the document. P.S. Want to compress the HTML as? Simply Replace "Ob_start ();" with "Ob_start (' Ob_gzhandler ')";
Refer to the Dev-tips article for the more information.
Copy Code code as follows:

<! DOCTYPE html>
<?php ob_start (' Ob_gzhandler ');?>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>untitled</title>
<body>

</body>
<?php Ob_end_flush ();?>

20. Protect your code to avoid SQL injection
Copy Code code as follows:

$username = mysql_real_escape_string ($GET [' username ']);
$id = $_get[' id '];
$statement = $connection->prepare ("SELECT * from tbl_members WHERE id =?");
$statement->bind_param ("i", $id);
$statement->execute ();

By using prepared statements, we never embed the user's inputted data directly into our query. Instead, we use the ' bind_param ' to bind the values (and escaping) to the query. Much safer, and, notably, faster when executing multiple CRUD statements at once.
21. Attempt ORM (Object Relational mapping)
ORM Libraries for PHP-like propel, and ORM are built into the PHP frameworks like cake.
22. Cache Database Driver page
Such as:
Copy Code code as follows:

Top of your script
$cachefile = ' cache/'. basename ($_server[' Script_uri '));
$cachetime = 120 * 60; 2 hours
Serve from the cache if it is younger than $cachetime
if (file_exists ($cachefile) && (Time ()-$cachetime < Filemtime ($cachefile)) {
Include ($cachefile);
echo "<!--Cached". Date (' JS F Y h:i ', Filemtime ($cachefile)). "-->";
Exit
}
Ob_start (); Start the output buffer
Your normal PHP script and HTML content here
BOTTOM of your script
$fp = fopen ($cachefile, ' w '); Open the cache file for writing
Fwrite ($FP, ob_get_contents ()); Save the contents of output buffer to the file
Fclose ($FP); Close the file
Ob_end_flush (); Send the output to the browser

23. Using the caching system
    • Memcached
    • Apc
    • XCache
    • Zend Cache
    • Eaccelerator
24. Verify Cookie Data
Cookie data, like any data passed on the Web, can is harmful. You can validate cookies data with either the Htmlspecialchars () or mysql_real_escape_string ().
25. Using a static file caching system
such as Smarty is a built-in cache of the powerful template system.
26. Analyze Your code
Profiling your code with a tool like Xdebug can help you to quickly spot bottlenecks and other potential problems in your PHP code. Some IDEs like Netbeans have PHP profiling capabilities as.
27. Coding Standard
such as Pear standard.
Keep functions Outside of Loops
You take a hit of performance to you include functions inside of loops. The larger the loop that you have, the longer the execution time would take. Take the extra time and line of the code and place the function outside the loop.
Editor ' s Note:think of it this way. Try to remove as many operations from the loop as possible. Do you really need to create this variable for every iteration of the loop? Do your really need to create the function of each time? Of course not.
29. Do not copy no additional variables (in fact this one is questionable, see the following note)
Such as:
Copy Code code as follows:

$description = strip_tags ($_post[' description '));
Echo $description;

Can be written as follows:
echo strip_tags ($_post[' description '));
Rebuttal:in reference to the comment about "doubling the memory," this actually is a common misconception. PHP implements "Copy-on-write" memory management. This basically means so you can assign a value of to as many variables as, like without have to worry about the data a Ctually being copied. While it's arguable that's "good" example exemplified above might make to cleaner code, I highly doubt that it's any Qu Icker.
In other words, PHP implementation of "Copy-on-write" memory management, the first of the above code does not occupy double memory. So rebuttal seriously doubt if the second way code is really faster than the front.
30. Update to the latest version of PHP
31. Reduce the number of database queries
32. Ask questions bravely
such as StackOverflow are good places to be.

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.