当前位置:Gxlcms > PHP教程 > 五十个PHP代码编写规范的技巧总结(推荐)

五十个PHP代码编写规范的技巧总结(推荐)

时间:2021-07-01 10:21:17 帮助过:8人阅读

php代码编写规范在php实际项目开发中是十分重要的,毕竟php代码的规范可以省去很多不必要的bug检查,下面的这篇文章我给大家分享了五十个PHP代码编写规范的技巧。

1,使用绝对路径,方便代码的迁移:

  1. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
  2. require_once(ROOT . '../../lib/some_class.php');
  3. * PATHINFO_DIRNAME 只返回 dirname
  4. * PATHINFO_BASENAME 只返回 basename
  5. * PATHINFO_EXTENSION 只返回 extension

2,不要直接使用 require, include, includeonce, requiredonce

  1. $path = ROOT . '/lib/' . $class_name . '.php');
  2. require_once( $path );
  3. * if(file_exists($path)){
  4. require_once( $path );
  5. }

3,为应用保留调试代码

  1. 在开发环境中, 我们打印数据库查询语句, 转存有问题的变量值,
  2. 而一旦问题解决, 我们注释或删除它们. 然而更好的做法是保留调试代码。
  3. 在开发环境中, 你可以:
  4. * define('ENVIRONMENT' , 'development');
  5. if(! $db->query( $query )
  6. {
  7. if(ENVIRONMENT == 'development')
  8. {
  9. echo "$query failed";
  10. }
  11. else {
  12. echo "Database error. Please contact administrator";
  13. }
  14. }
  15. * 在服务器中, 你可以:
  16. define('ENVIRONMENT' , 'production');
  17. if(! $db->query( $query )
  18. {
  19. if(ENVIRONMENT == 'development')
  20. {
  21. echo "$query failed";
  22. }
  23. else
  24. {
  25. echo "Database error. Please contact administrator";
  26. }
  27. }

4,使用可跨平台的函数执行命令

  1. system, exec, passthru, shell_exec 这4个函数可用于执行系统命令
  2. /**
  3. * Method to execute a command in the terminal
  4. * Uses :
  5. * 1. system
  6. * 2. passthru
  7. * 3. exec
  8. * 4. shell_exec
  9. */
  10. function terminal($command)
  11. {
  12. //system
  13. if (function_exists('system')) {
  14. ob_start(); // 打开缓冲区
  15. system($command, $return_var);
  16. $output = ob_get_contents();
  17. ob_end_clean(); // 清空(擦除)缓冲区并关闭
输出缓冲 } //passthru else if (function_exists('passthru')) { ob_start(); passthru($command, $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if (function_exists('exec')) { exec($command, $output, $return_var); $output = implode("\n", $output); } //shell_exec else if (function_exists('shell_exec')) { $output = shell_exec($command); } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output, 'status' => $return_var); } terminal('ls');

5,灵活编写函数(判断是否是数组来编写逻辑)

  1. function add_to_cart($item_id, $qty)
  2. {
  3. if (!is_array($item_id)) {
  4. $_SESSION['cart']['item_id'] = $qty;
  5. } else {
  6. foreach ($item_id as $i_id => $qty) {
  7. $_SESSION['cart']['i_id'] = $qty;
  8. }
  9. }
  10. }
  11. add_to_cart('IPHONE3', 2);
  12. add_to_cart(array('IPHONE3' => 2, 'IPAD' => 5));

6,有意忽略php关闭标签

  1. like: <?php ......................

7, 在某地方收集所有输入, 一次输出给浏览器 <重点>

  1. 你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean

8,发送正确的mime类型头信息, 如果输出非html内容的话. <重点>

  1. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
  2. $xml = "<response>
  3. <code>0</code>
  4. </response>";
  5. //Send xml data
  6. header("content-type: text/xml"); //注意header头部
  7. echo $xml;

9,为mysql连接设置正确的字符编码

  1. mysqli_set_charset(UTF8);

10,使用 htmlentities 设置正确的编码选项 <重点>

  1. php5.4前, 字符的默认编码是ISO-8859-1, 不能直接
输出如À â等. $value = htmlentities($this->value , ENT_QUOTES , CHARSET); php5.4后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍要留意编码问题.

11,不要在应用中使用gzip压缩输出, 让apache处理 <重点>

  1. 使用apache的mod_gzip/mod_deflate 模块压缩内容. 开启就行了。
  2. 用途:压缩和解压缩swf文件的代码等,PHP的zip扩展也行

12,使用json_encode输出动态javascript内容 而不是 echo

13,写文件前, 检查目录写权限

  1. linux系统
  2. is_readable($file_path)
  3. is_writable($file_path)

14,更改应用创建的文件权限

  1. chmod("/somedir/somefile", 0755);

15,不要依赖submit按钮值来检查表单提交行为

  1. if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
  2. {
  3. //Save the things
  4. }

16,为函数内总具有相同值的变量定义成静态变量

  1. static $sync_delay = null;

17,不要直接使用 $_SESSION 变量

  1. 不同的应用之前加上 不同的 前缀

18,將工具函数封装到类中(同个类维护多个版本, 而不导致冲突)

  1. class Utility
  2. {
  3. public static function utility_a()
  4. {
  5. }
  6. public static function utility_b()
  7. {
  8. }
  9. public static function utility_c()
  10. {
  11. }
  12. }
  13. $a = Utility::utility_a();
  14. $b = Utility::utility_b();

19,Bunch of silly tips

  1. >> 使用echo取代print
  2. >> 使用str_replace取代preg_replace, 除非你绝对需要
  3. >> 不要使用 short tag
  4. >> 简单字符串用单引号取代双引号
  5. >> head重定向后记得使用exit
  6. >> 不要在循环中调用函数
  7. >> isset比strlen快
  8. >> 始中如一的格式化代码
  9. >> 不要删除循环或者if-else的括号

20,使用array_map快速处理数组

  1. $arr = array_map('trim' , $string);

21,使用 php filter 验证数据 <重点> 可以尝试

22,强制类型检查: intval (int) (string)......

23, 如果需要,使用profiler( 优化PHP代码 ) 如 xdebug

24,小心处理大数组

  1. 确保通过引用传递, 或存储在类变量中:
  2. $a = get_large_array();
  3. pass_to_function(&$a); // 之后unset掉 释放资源

25,由始至终使用单一数据库连接

26,避免直接写SQL, 抽象之;自己封装函数数组,注意转义

27,將数据库生成的内容缓存到静态文件中

28,在数据库中保存session

29,避免使用全局变量

  1. >> 使用 defines/constants
  2. >> 使用函数获取值
  3. >> 使用类并通过$this访问

30,在head中使用base标签

  1. > www.domain.com/store/home.php
  2. > www.domain.com/store/products/ipad.php
  3. 改为:
  4. // 基础路由
  5. <base href="http://www.domain.com/store/">
  6. <a href="home.php">Home</a>
  7. <a href="products/ipad.php">Ipad</a>

31,永远不要將 error_reporting 设为 0

  1. error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);

32,注意平台体系结构

  1. integer在32位和64位体系结构中长度是不同的. 因此某些函数如 strtotime 的行为会不同.

33,不要过分依赖 settimelimit() <重要>

  1. 注意任何外部的执行, 如系统调用,socket操作, 数据库操作等, 就不在set_time_limits的控制之下
  2. * 一个php脚本通过crontab每5分钟执行一次
  3. * sleep函数暂停的时间也是不计入脚本的执行时间的

9,使用扩展库 <重要>

  1. >> mPDF — 能通过html生成pdf文档
  2. >> PHPExcel — 读写excel
  3. >> PhpMailer — 轻松处理发送包含附近的邮件
  4. >> pChart — 使用php生成报表

34,使用MVC框架

35,时常看看 phpbench

  1. 可以 php基本操作的基准测试结果,一般PHP框架 多是有的,具体看文档

36,如何正确的创建一个网站的Index页面

  1. 学习一种更高效的方式来实现PHP编程,可以采用“index.php?page=home”模式
  2. 如在CI中,可以通过 .htaccess /apache/nginx 的配置隐藏index.php

37,使用Request Global Array抓取数据

  1. $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0;

38,利用var_dump进行PHP代码调试

39,PHP处理代码逻辑,Smarty处理展现层

  1. PHP原生自带的Smarty渲染模板,laravel框架中是 balde模板(同理)

40,的确需要使用全局数值时,创建一个Config文件

41,如果未定义,禁止访问! (仿造Java等编译语言,PHP是弱类型的脚本语言的缘故)

  1. like define('wer',1);
  2. 在其他页面调用时会 if (!defined('wer')) die('Access Denied');

42,创建一个数据库类 (PHP框架一般集成了,不过封装原生的时候,可以参考)

43,一个php文件处理输入,一个class.php文件处理具体功能

44,了解你的SQL语句,并总是对其审查(Sanitize)

45, 当你只需要一个对象时,使用单例模式 (三私一公)

46,关于PHP重定向 方法一:header("Location:index.php");

  1. // 方法二 会引发浏览器的安全机制,不允许弹窗弹出
  2. 方法二:echo"<script>window.location=\"$PHP_SELF\";</script>";
  3. 方法三:echo"<METAHTTP-EQUIV=\"Refresh\"CONTENT=\"0;URL=index.php\">";

47,获取访问者浏览器

  1. functionbrowse_infor()
  2. {
  3. $browser = "";
  4. $browserver = "";
  5. $Browsers = array("Lynx", "MOSAIC", "AOL", "Opera", "JAVA", "MacWeb", "WebExplorer", "OmniWeb");
  6. $Agent = $GLOBALS["HTTP_USER_AGENT"];
  7. for ($i = 0; $i <= 7; $i++) {
  8. if (strpos($Agent, $Browsers[$i])) {
  9. $browser = $Browsers[$i];
  10. $browserver = "";
  11. }
  12. }
  13. if (ereg("Mozilla", $Agent) && !ereg("MSIE", $Agent)) {
  14. $temp = explode("(", $Agent);
  15. $Part = $temp[0];
  16. $temp = explode("/", $Part);
  17. $browserver = $temp[1];
  18. $temp = explode("", $browserver);
  19. $browserver = $temp[0];
  20. $browserver = preg_replace("/([\d\.]+)/", "\1", $browserver);
  21. $browserver = "$browserver";
  22. $browser = "NetscapeNavigator";
  23. }
  24. if (ereg("Mozilla", $Agent) && ereg("Opera", $Agent)) {
  25. $temp = explode("(", $Agent);
  26. $Part = $temp[1];
  27. $temp = explode(")", $Part);
  28. $browserver = $temp[1];
  29. $temp = explode("", $browserver);
  30. $browserver = $temp[2];
  31. $browserver = preg_replace("/([\d\.]+)/", "\1", $browserver);
  32. $browserver = "$browserver";
  33. $browser = "Opera";
  34. }
  35. if (ereg("Mozilla", $Agent) && ereg("MSIE", $Agent)) {
  36. $temp = explode("(", $Agent);
  37. $Part = $temp[1];
  38. $temp = explode(";", $Part);
  39. $Part = $temp[1];
  40. $temp = explode("", $Part);
  41. $browserver = $temp[2];
  42. $browserver = preg_replace("/([\d\.]+)/", "\1", $browserver);
  43. $browserver = "$browserver";
  44. $browser = "InternetExplorer";
  45. }
  46. if ($browser != "") {
  47. $browseinfo = "$browser$browserver";
  48. } else {
  49. $browseinfo = "Unknown";
  50. }
  51. return $browseinfo;
  52. }
  53. //调用方法$browser=browseinfo();直接返回结果

48.获取访问者操作系统

  1. <?php
  2. functionosinfo(){
  3. $os = "";
  4. $Agent = $GLOBALS["HTTP_USER_AGENT"];
  5. if (eregi('win', $Agent) && strpos($Agent, '95')) {
  6. $os = "Windows95";
  7. } elseif (eregi('win9x', $Agent) && strpos($Agent, '4.90')) {
  8. $os = "WindowsME";
  9. } elseif (eregi('win', $Agent) && ereg('98', $Agent)) {
  10. $os = "Windows98";
  11. } elseif (eregi('win', $Agent) && eregi('nt5\.0', $Agent)) {
  12. $os = "Windows2000";
  13. } elseif (eregi('win', $Agent) && eregi('nt', $Agent)) {
  14. $os = "WindowsNT";
  15. } elseif (eregi('win', $Agent) && eregi('nt5\.1', $Agent)) {
  16. $os = "WindowsXP";
  17. } elseif (eregi('win', $Agent) && ereg('32', $Agent)) {
  18. $os = "Windows32";
  19. } elseif (eregi('linux', $Agent)) {
  20. $os = "Linux";
  21. } elseif (eregi('unix', $Agent)) {
  22. $os = "Unix";
  23. } elseif (eregi('sun', $Agent) && eregi('os', $Agent)) {
  24. $os = "SunOS";
  25. } elseif (eregi('ibm', $Agent) && eregi('os', $Agent)) {
  26. $os = "IBMOS/2";
  27. } elseif (eregi('Mac', $Agent) && eregi('PC', $Agent)) {
  28. $os = "Macintosh";
  29. } elseif (eregi('PowerPC', $Agent)) {
  30. $os = "PowerPC";
  31. } elseif (eregi('AIX', $Agent)) {
  32. $os = "AIX";
  33. } elseif (eregi('HPUX', $Agent)) {
  34. $os = "HPUX";
  35. } elseif (eregi('NetBSD', $Agent)) {
  36. $os = "NetBSD";
  37. } elseif (eregi('BSD', $Agent)) {
  38. $os = "BSD";
  39. } elseif (ereg('OSF1', $Agent)) {
  40. $os = "OSF1";
  41. } elseif (ereg('IRIX', $Agent)) {
  42. $os = "IRIX";
  43. } elseif (eregi('FreeBSD', $Agent)) {
  44. $os = "FreeBSD";
  45. }
  46. if ($os == '') $os = "Unknown";
  47. return $os;
  48. }
  49. //调用方法$os=os_infor();

49,文件格式类

  1. $mime_types=array(
  2. 'gif'=>'image/gif',
  3. 'jpg'=>'image/jpeg',
  4. 'jpeg'=>'image/jpeg',
  5. 'jpe'=>'image/jpeg',
  6. 'bmp'=>'image/bmp',
  7. 'png'=>'image/png',
  8. 'tif'=>'image/tiff',
  9. 'tiff'=>'image/tiff',
  10. 'pict'=>'image/x-pict',
  11. 'pic'=>'image/x-pict',
  12. 'pct'=>'image/x-pict',
  13. 'tif'=>'image/tiff',
  14. 'tiff'=>'image/tiff',
  15. 'psd'=>'image/x-photoshop',
  16. 'swf'=>'application/x-shockwave-flash',
  17. 'js'=>'application/x-javascript',
  18. 'pdf'=>'application/pdf',
  19. 'ps'=>'application/postscript',
  20. 'eps'=>'application/postscript',
  21. 'ai'=>'application/postscript',
  22. 'wmf'=>'application/x-msmetafile',
  23. 'css'=>'text/css',
  24. 'htm'=>'text/html',
  25. 'html'=>'text/html',
  26. 'txt'=>'text/plain',
  27. 'xml'=>'text/xml',
  28. 'wml'=>'text/wml',
  29. 'wbmp'=>'image/vnd.wap.wbmp',
  30. 'mid'=>'audio/midi',
  31. 'wav'=>'audio/wav',
  32. 'mp3'=>'audio/mpeg',
  33. 'mp2'=>'audio/mpeg',
  34. 'avi'=>'video/x-msvideo',
  35. 'mpeg'=>'video/mpeg',
  36. 'mpg'=>'video/mpeg',
  37. 'qt'=>'video/quicktime',
  38. 'mov'=>'video/quicktime',
  39. 'lha'=>'application/x-lha',
  40. 'lzh'=>'application/x-lha',
  41. 'z'=>'application/x-compress',
  42. 'gtar'=>'application/x-gtar',
  43. 'gz'=>'application/x-gzip',
  44. 'gzip'=>'application/x-gzip',
  45. 'tgz'=>'application/x-gzip',
  46. 'tar'=>'application/x-tar',
  47. 'bz2'=>'application/bzip2',
  48. 'zip'=>'application/zip',
  49. 'arj'=>'application/x-arj',
  50. 'rar'=>'application/x-rar-compressed',
  51. 'hqx'=>'application/mac-binhex40',
  52. 'sit'=>'application/x-stuffit',
  53. 'bin'=>'application/x-macbinary',
  54. 'uu'=>'text/x-uuencode',
  55. 'uue'=>'text/x-uuencode',
  56. 'latex'=>'application/x-latex',
  57. 'ltx'=>'application/x-latex',
  58. 'tcl'=>'application/x-tcl',
  59. 'pgp'=>'application/pgp',
  60. 'asc'=>'application/pgp',
  61. 'exe'=>'application/x-msdownload',
  62. 'doc'=>'application/msword',
  63. 'rtf'=>'application/rtf',
  64. 'xls'=>'application/vnd.ms-excel',
  65. 'ppt'=>'application/vnd.ms-powerpoint',
  66. 'mdb'=>'application/x-msaccess',
  67. 'wri'=>'application/x-mswrite',
  68. );

50.php生成excel文档

  1. <?php
  2. header("Content-type:application/vnd.ms-excel");
  3. header("Content-Disposition:filename=test.xls");
  4. echo"test1\t";
  5. echo"test2\t\n";
  6. echo"test1\t";
  7. echo"test2\t\n";
  8. echo"test1\t";
  9. echo"test2\t\n";
  10. echo"test1\t";
  11. echo"test2\t\n";
  12. echo"test1\t";
  13. echo"test2\t\n";
  14. echo"test1\t";
  15. echo"test2\t\n";
  16. ?>
  17. //改动相应文件头就可以
输出.doc.xls等文件格式了

相关推荐:

PHP代码样式风格规范分享

你必须了解的10个编程的技巧

以上就是五十个PHP代码编写规范的技巧总结(推荐)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行