Home Backend Development PHP Tutorial 给初学者的30条PHP最佳实践(荒野无灯)_php技巧

给初学者的30条PHP最佳实践(荒野无灯)_php技巧

May 17, 2016 am 09:16 AM
Best Practices

1,和PHP手册成为好朋友
2,打开Error Reporting
Error reporting 在 PHP 开发时是很有帮助的. 你可以在你代码中发现先前你没有发现的错误,因为并不是所有的BUG都会让程序运行不了的。当产品正式使用时,才有必要关掉错误报告,不然顾客看到一堆奇怪的字符不知道那是什么意思。
3,使用IDE
IDE (集成开发环境,Integrated Development Environments)对于开发者来说是很有帮助的工具.
荒野在这里推荐netbeans IDE 。
4. 试着使用一个PHP 框架
5.学习DRY方法
DRY 代表 Don't Repeat Yourself,它是一个有价值的编程概念,不管是什么语言。DRY编程,顾名思义,是确保你不写多余的代码。
6.使用空格缩进代码来提高可读性
7. “Tier” your Code
给你的应用程序分层,分成不同部位的不同组成部分的代码。这使得您可以轻松地在未来改变你的代码。 如常用的MVC模式。
8. 总是使用
9.使用有意义的,一致的命名约定
10.注释、注释、注释
11.安装MAMP/WAMP
12.给你的脚本限制运行时间
通常PHP脚本的运行时间被限制为30秒,超过这个时间PHP将抛出一个致命错误。
13.使用OOP
14.知道双引号和单引号的不同
15.不要在网站的根目录放phpinfo()
16.永远不要信任你的用户
17.加密存储密码
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.使用可视化数据库设计工具
如 DBDesigner 和 MySQL Workbench
19.使用输出缓冲
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.

复制代码 代码如下:






untitled







20.保护你的代码避免SQL注射
复制代码 代码如下:

$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.尝试ORM (object relational mapping)
ORM libraries for PHP like Propel, and ORM is built into PHP frameworks like CakePHP.
22.缓存数据库驱动页面
如:
复制代码 代码如下:

// 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 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.使用缓存系统
24.验证Cookie数据
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.使用静态文件缓存系统
如Smarty的是一个内置缓存的强大的模板系统。
26.分析你的代码
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.编码标准
如 Pear标准。
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.不要复制不额外的变量(事实上这一条值得怀疑,见下面的说明)
如:
复制代码 代码如下:

$description = strip_tags($_POST['description']);
echo $description;

可以写成如下:
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 data actually being copied. While it's arguable that the “Good” example exemplified above might make for cleaner code, I highly doubt that it's any quicker.
也就是说PHP实现“copy-on-write” 的内存管理方式,上面第一种代码并不会存在占用双倍内存的情况。因此Rebuttal严重怀疑第二种方式的代码是否真的比前面的快。
30.更新到最新版本的PHP
31.减少数据库查询次数
32.勇敢地提问
StackOverflow等都是好去处。
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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

Best practices for converting strings to floating point numbers in PHP Best practices for converting strings to floating point numbers in PHP Mar 28, 2024 am 08:18 AM

Converting strings to floating point numbers in PHP is a common requirement during the development process. For example, the amount field read from the database is of string type and needs to be converted into floating point numbers for numerical calculations. In this article, we will introduce the best practices for converting strings to floating point numbers in PHP and give specific code examples. First of all, we need to make it clear that there are two main ways to convert strings to floating point numbers in PHP: using (float) type conversion or using (floatval) function. Below we will introduce these two

What are the best practices for string concatenation in Golang? What are the best practices for string concatenation in Golang? Mar 14, 2024 am 08:39 AM

What are the best practices for string concatenation in Golang? In Golang, string concatenation is a common operation, but efficiency and performance must be taken into consideration. When dealing with a large number of string concatenations, choosing the appropriate method can significantly improve the performance of the program. The following will introduce several best practices for string concatenation in Golang, with specific code examples. Using the Join function of the strings package In Golang, using the Join function of the strings package is an efficient string splicing method.

PHP Best Practices: Alternatives to Avoiding Goto Statements Explored PHP Best Practices: Alternatives to Avoiding Goto Statements Explored Mar 28, 2024 pm 04:57 PM

PHP Best Practices: Alternatives to Avoiding Goto Statements Explored In PHP programming, a goto statement is a control structure that allows a direct jump to another location in a program. Although the goto statement can simplify code structure and flow control, its use is widely considered to be a bad practice because it can easily lead to code confusion, reduced readability, and debugging difficulties. In actual development, in order to avoid using goto statements, we need to find alternative methods to achieve the same function. This article will explore some alternatives,

Explore best practices for indentation in Go Explore best practices for indentation in Go Mar 21, 2024 pm 06:48 PM

In Go language, good indentation is the key to code readability. When writing code, a unified indentation style can make the code clearer and easier to understand. This article will explore the best practices for indentation in the Go language and provide specific code examples. Use spaces instead of tabs In Go, it is recommended to use spaces instead of tabs for indentation. This can avoid typesetting problems caused by inconsistent tab widths in different editors. The number of spaces for indentation. Go language officially recommends using 4 spaces as the number of spaces for indentation. This allows the code to be

What are the best practices for the golang framework? What are the best practices for the golang framework? Jun 01, 2024 am 10:30 AM

When using Go frameworks, best practices include: Choose a lightweight framework such as Gin or Echo. Follow RESTful principles and use standard HTTP verbs and formats. Leverage middleware to simplify tasks such as authentication and logging. Handle errors correctly, using error types and meaningful messages. Write unit and integration tests to ensure the application is functioning properly.

Naming conventions and best practices for PHP methods Naming conventions and best practices for PHP methods Feb 29, 2024 pm 01:51 PM

Naming Conventions and Best Practices for PHP Methods As a popular server-side scripting language, PHP is widely used to develop websites and web applications. In PHP development, methods (functions) are a very important part. Good naming conventions and best practices can improve the readability, maintainability and scalability of the code. This article will share some norms and best practices about PHP method naming, while providing specific code examples. Method naming convention 1. Use meaningful and descriptive names. The name of a method should accurately describe the method.

The role and best practices of .env files in Laravel development The role and best practices of .env files in Laravel development Mar 10, 2024 pm 03:03 PM

The role and best practices of .env files in Laravel development In Laravel application development, .env files are considered to be one of the most important files. It carries some key configuration information, such as database connection information, application environment, application keys, etc. In this article, we’ll take a deep dive into the role of .env files and best practices, along with concrete code examples. 1. The role of the .env file First, we need to understand the role of the .env file. In a Laravel should

In-depth comparison: best practices between Java frameworks and other language frameworks In-depth comparison: best practices between Java frameworks and other language frameworks Jun 04, 2024 pm 07:51 PM

Java frameworks are suitable for projects where cross-platform, stability and scalability are crucial. For Java projects, Spring Framework is used for dependency injection and aspect-oriented programming, and best practices include using SpringBean and SpringBeanFactory. Hibernate is used for object-relational mapping, and best practice is to use HQL for complex queries. JakartaEE is used for enterprise application development, and the best practice is to use EJB for distributed business logic.

See all articles