Home  >  Article  >  Backend Development  >  30 PHP best practices for beginners (no lights in the wilderness)_PHP tutorial

30 PHP best practices for beginners (no lights in the wilderness)_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:25:551233browse

1. Become good friends with the PHP manual
2. Turn on Error Reporting
Error reporting is very helpful when developing PHP. You can find errors in your code that you have not found before, because not all Bugs will prevent the program from running. When the product is officially used, it is necessary to turn off error reporting, otherwise customers will see a bunch of strange characters and not know what they mean.
3. Use IDE
IDE (Integrated Development Environments) is a very helpful tool for developers.
The wilderness recommends netbeans IDE here.
4. Try to use a PHP framework
5. Learn the DRY method
DRY stands for Don't Repeat Yourself, it is a valuable programming concept, no matter what language it is. DRY programming, as the name suggests, ensures that you don't write redundant code.
6. Use spaces to indent code to improve readability
7. “Tier” your Code
Tier your application into different parts of the code. This allows you to easily change your code in the future. Such as the commonly used MVC pattern.
8. Always use
9. Use meaningful, consistent naming conventions
10. Comment, comment, comment
11. Install MAMP/WAMP
12. Limit the running time of your script
Usually the running time of PHP scripts is limited to 30 seconds, after which PHP will throw a fatal error.
13. Use OOP
14. Know the difference between double quotes and single quotes
15. Don’t put phpinfo() in the root directory of the website
16. Never trust your users
17 .Encrypted storage of passwords
Rebuttal:
Keep in mind, however, that MD5 hashes have long since been compromised. They're absolutely more secure than not, but, with the use of an enormous “rainbow table,” hackers can cross reference your hash. To add even more security, consider adding a salt as well. A salt is basically an additional set of characters that you append to the user's string.
18. Use visual database design tools
as DBDesigner and MySQL Workbench
19. Using output buffering
Rebuttal: Though not required, it's generally considered to be a good practice to go ahead and append the “ob_end_flush();” function as well to the bottom of the document . P.S. Want to compress the HTML as well? Simply replace “ob_start();” with “ob_start('ob_gzhandler’)”;
Refer to this Dev-tips article for more information.

Copy code The code is as follows:






untitled







20. Protect your code from SQL injection
Copy code The code is 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” method to bind the values ​​(and escaping) to the query. Much safer, and, notably, faster when executing multiple CRUD statements at once.
21. Try ORM (object relational mapping)
ORM libraries for PHP like Propel, and ORM is built into PHP frameworks like CakePHP.
22. Cache database driver pages
Such as:
Copy code The code is 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 "";
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. Use caching system
  • Memcached
  • APC
  • XCache
  • Zend Cache
  • eAccelerator
24. Validate Cookie data
Cookie data, like any data passed on the Web, can be harmful. You can validate cookie data with either the htmlspecialchars() or mysql_real_escape_string().
25. Use a static file caching system
Such as Smarty is a powerful template system with built-in caching.
26. Profiling 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 well.
27. Coding standards
such as Pear standard.
28. Keep Functions Outside of Loops
You take a hit of performance when you include functions inside of loops. The larger the loop that you have, the longer the execution time will take. Take the extra time and line of code and place the function outside of 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 that variable for every iteration of the loop? Do you really need to create the function each time? Of course not.
29. Do not copy additional variables (in fact this is questionable, see the explanation below)
For example:
Copy code The code is 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 that you can assign a value to as many variables as you like without having to worry about the copied data actually being. While it's arguable that the "Good" example exemplified above might make for cleaner code, I highly doubt that it's any quicker.
That is to say, PHP implements the "copy-on-write" memory management method. The first code above will not occupy double the memory. Therefore, Rebuttal seriously doubts whether the second method of code is really faster than the previous one.
30. Update to the latest version of PHP
31. Reduce the number of database queries
32. Ask questions bravely
places like StackOverflow are good places.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324069.htmlTechArticle1. Become good friends with the PHP manual 2. Turn on Error Reporting Error reporting is very helpful when developing PHP . You can find bugs in your code that you didn't catch before because...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn