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


Posted in PHP onAugust 02, 2011

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. 总是使用 <?php ?>
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.

<!DOCTYPE html> 
<?php ob_start('ob_gzhandler'); ?> 
<html lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>untitled</title> 
</head> 
<body> </body> 
</html> 
<?php ob_end_flush(); ?>

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 < 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.使用缓存系统
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等都是好去处。
PHP 相关文章推荐
杏林同学录(三)
Oct 09 PHP
无刷新动态加载数据 滚动条加载适合评论等页面
Oct 16 PHP
PHP获取php,mysql,apche的版本信息示例代码
Jan 16 PHP
php+mysql实现无限分类实例详解
Jan 15 PHP
PHP实现在线阅读PDF文件的方法
Jun 23 PHP
Thinkphp和Bootstrap结合打造个性的分页样式(推荐)
Aug 01 PHP
浅谈PHP面向对象之访问者模式+组合模式
May 22 PHP
解决安装WampServer时提示缺少msvcr110.dll文件的问题
Jul 09 PHP
详解php中curl返回false的解决办法
Mar 18 PHP
ThinkPHP5&amp;5.1框架关联模型分页操作示例
Aug 03 PHP
php 中self,this的区别和操作方法实例分析
Nov 04 PHP
php判断数组是否为空的实例方法
May 10 PHP
使用ThinkPHP自带的Http类下载远程图片到本地的实现代码
Aug 02 #PHP
linux下使用ThinkPHP需要注意大小写导致的问题
Aug 02 #PHP
理解和运用PHP中的多态性[译]
Aug 02 #PHP
应用开发中涉及到的css和php笔记分享
Aug 02 #PHP
PHP源代码数组统计count分析
Aug 02 #PHP
linux下为php添加curl扩展的方法
Jul 29 #PHP
php中修改浏览器的User-Agent来伪装你的浏览器和操作系统
Jul 29 #PHP
You might like
PHP封装CURL扩展类实例
2015/07/28 PHP
ThinkPHP表单令牌错误的相关解决方法分析
2016/05/20 PHP
让AJAX不依赖后端接口实现方案
2012/12/03 Javascript
JS完整获取IE浏览器信息包括类型、版本、语言等等
2014/05/22 Javascript
ECMAScript6块级作用域及新变量声明(let)
2015/06/12 Javascript
详解js跨域原理以及2种解决方案
2015/12/09 Javascript
详解javascript跨浏览器事件处理程序
2016/03/27 Javascript
原生JavaScript实现Ajax异步请求
2017/11/19 Javascript
微信小程序出现wx.navigateTo页面不跳转问题的解决方法
2017/12/26 Javascript
微信小程序如何获取手机验证码
2018/11/04 Javascript
使用Vue.observable()进行状态管理的实例代码详解
2019/05/26 Javascript
浅析vue中的provide / inject 有什么用处
2019/11/10 Javascript
谈谈JavaScript令人迷惑的==与+
2020/08/31 Javascript
python的迭代器与生成器实例详解
2014/07/16 Python
零基础写python爬虫之打包生成exe文件
2014/11/06 Python
Bottle框架中的装饰器类和描述符应用详解
2017/10/28 Python
pyqt5与matplotlib的完美结合实例
2019/06/21 Python
tensorboard 可以显示graph,却不能显示scalar的解决方式
2020/02/15 Python
Python 多线程共享变量的实现示例
2020/04/17 Python
Python实现CAN报文转换工具教程
2020/05/05 Python
学习Python爬虫的几点建议
2020/08/05 Python
python使用建议技巧分享(三)
2020/08/18 Python
Python操控mysql批量插入数据的实现方法
2020/10/27 Python
CSS3贝塞尔曲线示例:创建链接悬停动画效果
2020/11/19 HTML / CSS
美国最受欢迎的度假租赁网站:VRBO
2016/08/02 全球购物
优秀的导游求职信范文
2014/04/06 职场文书
节水倡议书范文
2014/04/15 职场文书
政风行风整改方案
2014/10/25 职场文书
公务员年终个人总结
2015/02/12 职场文书
党校毕业个人总结
2015/02/28 职场文书
导游词之绍兴柯岩古镇
2020/01/09 职场文书
Java基础之线程锁相关知识总结
2021/06/30 Java/Android
django 认证类配置实现
2021/11/11 Python
Python各协议下socket黏包问题原理
2022/04/12 Python
Windows Server 2019 安装DHCP服务及相关配置
2022/04/28 Servers
Mysql数据库事务的脏读幻读及不可重复读详解
2022/05/30 MySQL