给初学者的30条PHP最佳实践(荒野无灯)
PHP 实践 最佳 30 初学者
2023-06-13 09:14:29 时间
1,和PHP手册成为好朋友
2,打开ErrorReporting
Errorreporting在PHP开发时是很有帮助的.你可以在你代码中发现先前你没有发现的错误,因为并不是所有的BUG都会让程序运行不了的。当产品正式使用时,才有必要关掉错误报告,不然顾客看到一堆奇怪的字符不知道那是什么意思。
3,使用IDE
IDE(集成开发环境,IntegratedDevelopmentEnvironments)对于开发者来说是很有帮助的工具.
荒野在这里推荐netbeansIDE。
4.试着使用一个PHP框架
5.学习DRY方法
DRY代表Don"tRepeatYourself,它是一个有价值的编程概念,不管是什么语言。DRY编程,顾名思义,是确保你不写多余的代码。
6.使用空格缩进代码来提高可读性
7.“Tier”yourCode
给你的应用程序分层,分成不同部位的不同组成部分的代码。这使得您可以轻松地在未来改变你的代码。如常用的MVC模式。
8.总是使用<?php?>
9.使用有意义的,一致的命名约定
10.注释、注释、注释
11.安装MAMP/WAMP
12.给你的脚本限制运行时间
通常PHP脚本的运行时间被限制为30秒,超过这个时间PHP将抛出一个致命错误。
13.使用OOP
14.知道双引号和单引号的不同
15.不要在网站的根目录放phpinfo()
16.永远不要信任你的用户
17.加密存储密码
Rebuttal:
Keepinmind,however,thatMD5hasheshavelongsincebeencompromised.They"reabsolutelymoresecurethannot,but,withtheuseofanenormous“rainbowtable,”hackerscancrossreferenceyourhash.Toaddevenmoresecurity,consideraddingasaltaswell.Asaltisbasicallyanadditionalsetofcharactersthatyouappendtotheuser"sstring.
18.使用可视化数据库设计工具
如DBDesigner和MySQLWorkbench
19.使用输出缓冲
Rebuttal:Thoughnotrequired,it"sgenerallyconsideredtobeagoodpracticetogoaheadandappendthe“ob_end_flush();”functionaswelltothebottomofthedocument.P.S.WanttocompresstheHTMLaswell?Simplyreplace“ob_start();”with“ob_start(‘ob_gzhandler")”;
RefertothisDev-tipsarticleformoreinformation.
复制代码代码如下:
2,打开ErrorReporting
Errorreporting在PHP开发时是很有帮助的.你可以在你代码中发现先前你没有发现的错误,因为并不是所有的BUG都会让程序运行不了的。当产品正式使用时,才有必要关掉错误报告,不然顾客看到一堆奇怪的字符不知道那是什么意思。
3,使用IDE
IDE(集成开发环境,IntegratedDevelopmentEnvironments)对于开发者来说是很有帮助的工具.
荒野在这里推荐netbeansIDE。
4.试着使用一个PHP框架
5.学习DRY方法
DRY代表Don"tRepeatYourself,它是一个有价值的编程概念,不管是什么语言。DRY编程,顾名思义,是确保你不写多余的代码。
6.使用空格缩进代码来提高可读性
7.“Tier”yourCode
给你的应用程序分层,分成不同部位的不同组成部分的代码。这使得您可以轻松地在未来改变你的代码。如常用的MVC模式。
8.总是使用<?php?>
9.使用有意义的,一致的命名约定
10.注释、注释、注释
11.安装MAMP/WAMP
12.给你的脚本限制运行时间
通常PHP脚本的运行时间被限制为30秒,超过这个时间PHP将抛出一个致命错误。
13.使用OOP
14.知道双引号和单引号的不同
15.不要在网站的根目录放phpinfo()
16.永远不要信任你的用户
17.加密存储密码
Rebuttal:
Keepinmind,however,thatMD5hasheshavelongsincebeencompromised.They"reabsolutelymoresecurethannot,but,withtheuseofanenormous“rainbowtable,”hackerscancrossreferenceyourhash.Toaddevenmoresecurity,consideraddingasaltaswell.Asaltisbasicallyanadditionalsetofcharactersthatyouappendtotheuser"sstring.
18.使用可视化数据库设计工具
如DBDesigner和MySQLWorkbench
19.使用输出缓冲
Rebuttal:Thoughnotrequired,it"sgenerallyconsideredtobeagoodpracticetogoaheadandappendthe“ob_end_flush();”functionaswelltothebottomofthedocument.P.S.WanttocompresstheHTMLaswell?Simplyreplace“ob_start();”with“ob_start(‘ob_gzhandler")”;
RefertothisDev-tipsarticleformoreinformation.
<!DOCTYPEhtml>
<?phpob_start("ob_gzhandler");?>
<htmllang="en">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>untitled</title>
</head>
<body>
</body>
</html>
<?phpob_end_flush();?>
20.保护你的代码避免SQL注射
$username=mysql_real_escape_string($GET["username"]);
$id=$_GET["id"];
$statement=$connection->prepare("SELECT*FROMtbl_membersWHEREid=?");
$statement->bind_param("i",$id);
$statement->execute();
Byusingpreparedstatements,weneverembedtheuser"sinputteddatadirectlyintoourquery.Instead,weusethe“bind_param”methodtobindthevalues(andescaping)tothequery.Muchsafer,and,notably,fasterwhenexecutingmultipleCRUDstatementsatonce.
21.尝试ORM (objectrelationalmapping)
ORMlibrariesforPHPlikePropel,andORMisbuiltintoPHPframeworkslikeCakePHP.
22.缓存数据库驱动页面
如:
//TOPofyourscript
$cachefile="cache/".basename($_SERVER["SCRIPT_URI"]);
$cachetime=120*60;//2hours
//Servefromthecacheifitisyoungerthan$cachetime
if(file_exists($cachefile)&&(time()-$cachetime<filemtime($cachefile))){
include($cachefile);
echo"<!--Cached".date("jSFYH:i",filemtime($cachefile))."-->";
exit;
}
ob_start();//starttheoutputbuffer
//YournormalPHPscriptandHTMLcontenthere
//BOTTOMofyourscript
$fp=fopen($cachefile,"w");//openthecachefileforwriting
fwrite($fp,ob_get_contents());//savethecontentsofoutputbuffertothefile
fclose($fp);//closethefile
ob_end_flush();//Sendtheoutputtothebrowser
23.使用缓存系统
Cookiedata,likeanydatapassedontheWeb,canbeharmful.Youcanvalidatecookiedatawitheitherthehtmlspecialchars()ormysql_real_escape_string().
25.使用静态文件缓存系统
如Smarty的是一个内置缓存的强大的模板系统。
26.分析你的代码
ProfilingyourcodewithatoollikexdebugcanhelpyoutoquicklyspotbottlenecksandotherpotentialproblemsinyourPHPcode.SomeIDEslikeNetbeanshavePHPprofilingcapabilitiesaswell.
27.编码标准
如Pear标准。
28.KeepFunctionsOutsideofLoops
Youtakeahitofperformancewhenyouincludefunctionsinsideofloops.Thelargertheloopthatyouhave,thelongertheexecutiontimewilltake.Taketheextratimeandlineofcodeandplacethefunctionoutsideoftheloop.
Editor"sNote:Thinkofitthisway.Trytoremoveasmanyoperationsfromtheloopaspossible.Doyoureallyneedtocreatethatvariableforeveryiterationoftheloop?Doyoureallyneedtocreatethefunctioneachtime?Ofcoursenot.
29.不要复制不额外的变量(事实上这一条值得怀疑,见下面的说明)
如:
$description=strip_tags($_POST["description"]);
echo$description;
可以写成如下:
echostrip_tags($_POST["description"]);
Rebuttal:Inreferencetothecommentabout“doublingthememory,”thisactuallyisacommonmisconception.PHPimplements“copy-on-write”memorymanagement.Thisbasicallymeansthatyoucanassignavaluetoasmanyvariablesasyoulikewithouthavingtoworryaboutthedataactuallybeingcopied.Whileit"sarguablethatthe“Good”exampleexemplifiedabovemightmakeforcleanercode,Ihighlydoubtthatit"sanyquicker.
也就是说PHP实现“copy-on-write”的内存管理方式,上面第一种代码并不会存在占用双倍内存的情况。因此Rebuttal严重怀疑第二种方式的代码是否真的比前面的快。
30.更新到最新版本的PHP
31.减少数据库查询次数
32.勇敢地提问
像StackOverflow等都是好去处。
相关文章
- php中利用header设置content-type和常见文件类型的content-type
- 微信授权网页扫码登录php,PHP实现微信开放平台扫码登录源码
- 【说站】如何打开php项目
- 【笔记php】如何使用PHP从JSON提取数据?
- 如何使用PHP连接MySQL数据库(php如何关联mysql)
- MySQL与PHP设置时区(mysql时区php)
- PHP与MySQL融合,尽享轻松开发(php与mysql整合)
- PHP使用MySQL数据库:最佳实践(php查询mysql数据库)
- Linux下PHP性能优化实践(linuxphp性能)
- 解决PHP MySQL超时问题的最佳实践(phpmysql超时)
- MySQL在PHP中的灵活运用(php中的mysql)
- 安装Linux环境的PHP扩展指南(linux安装php扩展)
- PHP中实现Redis队列的挑战与实践(php队列redis)
- 程序快速学会在Linux中执行PHP程序(linux执行php)
- MySQL备份之用PHP编程(mysql备份php)
- 监控Redis运行状态:妙用PHP(php监听redis)
- PHP与MSSQL:高效开发数据驱动应用程序(php与mssql)
- Linux 环境下验证 PHP性能(linux验证php)
- 驱动开发:PHP框架与MongoDB的结合(php框架mongodb)
- 重启Linux服务器,以使PHP生效(php重启linux)
- PHP与MySQL圣经:完整指南及最佳实践。(php与mysql圣经)
- 基于PHP的Redis视频教程(redis视频教程php)
- PHP解决MSSQL数据库乱码问题(php解决mssql乱码)
- 仅用PHP操作MSSQL,实现快速下载!(php mssql下载)
- Linux环境下的PHP脚本开发与应用(linux下php脚本)
- 逐步提升php框架的性能
- 40个迹象表明你还是PHP菜鸟
- php读取msn上的用户信息类
- PHP教程预定义变量
- 20个非常有用的PHP类库加速php开发
- 微盾PHP脚本加密专家php解密算法
- PHP和Mysqlweb应用开发核心技术第1部分Php基础-1开始了解php
- php定时计划任务的实现方法详解
- 通过php删除xml文档内容的方法