Home Backend Development PHP Tutorial 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

Jul 21, 2016 pm 03:25 PM
error php beginner and practice become manual Open optimal of

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

See all articles