Home > Backend Development > PHP Tutorial > Summary of fifty skills for PHP code writing standards (recommended)

Summary of fifty skills for PHP code writing standards (recommended)

不言
Release: 2023-04-03 13:00:02
Original
1945 people have browsed it

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

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

 define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
 require_once(ROOT . '../../lib/some_class.php');

 * PATHINFO_DIRNAME     只返回 dirname
 * PATHINFO_BASENAME    只返回 basename
 * PATHINFO_EXTENSION   只返回 extension
Copy after login

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

$path = ROOT . '/lib/' . $class_name . '.php');
require_once( $path );

* if(file_exists($path)){
     require_once( $path );
    }
Copy after login

3,为应用保留调试代码

在开发环境中, 我们打印数据库查询语句, 转存有问题的变量值, 
而一旦问题解决, 我们注释或删除它们. 然而更好的做法是保留调试代码。
在开发环境中, 你可以:

* define('ENVIRONMENT' , 'development');
  if(! $db->query( $query )
 {
   if(ENVIRONMENT == 'development')
  { 
      echo "$query failed";
  }
 else {
 echo "Database error. Please contact administrator";
     }
 }

* 在服务器中, 你可以:

define('ENVIRONMENT' , 'production');
if(! $db->query( $query )
{
   if(ENVIRONMENT == 'development')
  {
   echo "$query failed";
  }
 else
  {
   echo "Database error. Please contact administrator";
  }
}
Copy after login

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

system, exec, passthru, shell_exec 这4个函数可用于执行系统命令

/**
  * Method to execute a command in the terminal
  * Uses :
  * 1. system
  * 2. passthru
  * 3. exec
  * 4. shell_exec
  */
function terminal($command)
{
//system
if (function_exists('system')) {
    ob_start();  // 打开缓冲区
    system($command, $return_var);
    $output = ob_get_contents();
    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');
Copy after login

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

function add_to_cart($item_id, $qty)
{
    if (!is_array($item_id)) {
        $_SESSION['cart']['item_id'] = $qty;
    } else {
        foreach ($item_id as $i_id => $qty) {
            $_SESSION['cart']['i_id'] = $qty;
        }
    }
}

add_to_cart('IPHONE3', 2);
add_to_cart(array('IPHONE3' => 2, 'IPAD' => 5));
Copy after login

6,有意忽略php关闭标签

like:   <?php  ......................
Copy after login

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

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

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

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
<code>0</code>
</response>";
//Send xml data
header("content-type: text/xml"); //注意header头部
echo $xml;
Copy after login

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

mysqli_set_charset(UTF8);
Copy after login

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

php5.4前, 字符的默认编码是ISO-8859-1, 不能直接输出如À â等.

$value = htmlentities($this->value , ENT_QUOTES , CHARSET);
php5.4后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍要留意编码问题.
Copy after login

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

使用apache的mod_gzip/mod_deflate 模块压缩内容.  开启就行了。

用途:压缩和解压缩swf文件的代码等,PHP的zip扩展也行
Copy after login

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

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

linux系统
is_readable($file_path)
is_writable($file_path)
Copy after login

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

chmod("/somedir/somefile", 0755);
Copy after login

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

if( $_SERVER[&#39;REQUEST_METHOD&#39;] == &#39;POST&#39; and isset($_POST[&#39;submit&#39;]) )
{
    //Save the things
}
Copy after login

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

static $sync_delay = null;
Copy after login

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

不同的应用之前加上   不同的 前缀
Copy after login

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

class Utility
{
 public static function utility_a()
 {
 }
 public static function utility_b()
 {
 }
 public static function utility_c()
 {
 }
}
 $a = Utility::utility_a();
 $b = Utility::utility_b();
Copy after login

19,Bunch of silly tips

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

20,使用array_map快速处理数组

  $arr = array_map(&#39;trim&#39; , $string);
Copy after login

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

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

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

24,小心处理大数组

确保通过引用传递, 或存储在类变量中:

$a = get_large_array();
pass_to_function(&$a); // 之后unset掉 释放资源
Copy after login

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

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

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

28,在数据库中保存session

29,避免使用全局变量

>> 使用 defines/constants 
>> 使用函数获取值 
>> 使用类并通过$this访问
Copy after login

30,在head中使用base标签

 > www.domain.com/store/home.php 
 > www.domain.com/store/products/ipad.php 

 改为:

// 基础路由
<base href="http://www.domain.com/store/">

<a href="home.php">Home</a>
<a href="products/ipad.php">Ipad</a>
Copy after login

31,永远不要將 error_reporting 设为 0

error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
Copy after login

32,注意平台体系结构

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

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

注意任何外部的执行, 如系统调用,socket操作, 数据库操作等, 就不在set_time_limits的控制之下

* 一个php脚本通过crontab每5分钟执行一次
* sleep函数暂停的时间也是不计入脚本的执行时间的
Copy after login

9,使用扩展库 <重要>

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

34,使用MVC框架

35,时常看看 phpbench

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

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

学习一种更高效的方式来实现PHP编程,可以采用“index.php?page=home”模式

如在CI中,可以通过  .htaccess  /apache/nginx 的配置隐藏index.php
Copy after login

37,使用Request Global Array抓取数据

$action = isset($_REQUEST[&#39;action&#39;]) ? $_REQUEST[&#39;action&#39;] : 0;
Copy after login

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

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

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

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

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

like    define(&#39;wer&#39;,1);

在其他页面调用时会  if (!defined(&#39;wer&#39;)) die(&#39;Access Denied&#39;);
Copy after login

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

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

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

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

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

 // 方法二  会引发浏览器的安全机制,不允许弹窗弹出
 方法二:echo"<script>window.location=\"$PHP_SELF\";</script>"; 

 方法三:echo"<METAHTTP-EQUIV=\"Refresh\"CONTENT=\"0;URL=index.php\">";
Copy after login

47,获取访问者浏览器

functionbrowse_infor()
{
  $browser = "";
  $browserver = "";
  $Browsers = array("Lynx", "MOSAIC", "AOL", "Opera", "JAVA", "MacWeb", "WebExplorer", "OmniWeb");
  $Agent = $GLOBALS["HTTP_USER_AGENT"];

for ($i = 0; $i <= 7; $i++) {
  if (strpos($Agent, $Browsers[$i])) {
      $browser = $Browsers[$i];
      $browserver = "";
  }
}
if (ereg("Mozilla", $Agent) && !ereg("MSIE", $Agent)) {
    $temp = explode("(", $Agent);
    $Part = $temp[0];
    $temp = explode("/", $Part);
    $browserver = $temp[1];
    $temp = explode("", $browserver);
    $browserver = $temp[0];
    $browserver = preg_replace("/([\d\.]+)/", "\1", $browserver);
    $browserver = "$browserver";
    $browser = "NetscapeNavigator";
}
if (ereg("Mozilla", $Agent) && ereg("Opera", $Agent)) {
    $temp = explode("(", $Agent);
    $Part = $temp[1];
    $temp = explode(")", $Part);
    $browserver = $temp[1];
    $temp = explode("", $browserver);
    $browserver = $temp[2];
    $browserver = preg_replace("/([\d\.]+)/", "\1", $browserver);
    $browserver = "$browserver";
    $browser = "Opera";
}
if (ereg("Mozilla", $Agent) && ereg("MSIE", $Agent)) {
    $temp = explode("(", $Agent);
    $Part = $temp[1];
    $temp = explode(";", $Part);
    $Part = $temp[1];
    $temp = explode("", $Part);
    $browserver = $temp[2];
    $browserver = preg_replace("/([\d\.]+)/", "\1", $browserver);
    $browserver = "$browserver";
    $browser = "InternetExplorer";
}
if ($browser != "") {
    $browseinfo = "$browser$browserver";
} else {
    $browseinfo = "Unknown";
}
return $browseinfo;
}

//调用方法$browser=browseinfo();直接返回结果
Copy after login

48.获取访问者操作系统

 <?php
 functionosinfo(){
   $os = "";
   $Agent = $GLOBALS["HTTP_USER_AGENT"];
 if (eregi(&#39;win&#39;, $Agent) && strpos($Agent, &#39;95&#39;)) {
     $os = "Windows95";
 } elseif (eregi(&#39;win9x&#39;, $Agent) && strpos($Agent, &#39;4.90&#39;)) {
     $os = "WindowsME";
 } elseif (eregi(&#39;win&#39;, $Agent) && ereg(&#39;98&#39;, $Agent)) {
     $os = "Windows98";
 } elseif (eregi(&#39;win&#39;, $Agent) && eregi(&#39;nt5\.0&#39;, $Agent)) {
     $os = "Windows2000";
 } elseif (eregi(&#39;win&#39;, $Agent) && eregi(&#39;nt&#39;, $Agent)) {
     $os = "WindowsNT";
 } elseif (eregi(&#39;win&#39;, $Agent) && eregi(&#39;nt5\.1&#39;, $Agent)) {
     $os = "WindowsXP";
 } elseif (eregi(&#39;win&#39;, $Agent) && ereg(&#39;32&#39;, $Agent)) {
     $os = "Windows32";
 } elseif (eregi(&#39;linux&#39;, $Agent)) {
     $os = "Linux";
 } elseif (eregi(&#39;unix&#39;, $Agent)) {
     $os = "Unix";
 } elseif (eregi(&#39;sun&#39;, $Agent) && eregi(&#39;os&#39;, $Agent)) {
     $os = "SunOS";
 } elseif (eregi(&#39;ibm&#39;, $Agent) && eregi(&#39;os&#39;, $Agent)) {
     $os = "IBMOS/2";
 } elseif (eregi(&#39;Mac&#39;, $Agent) && eregi(&#39;PC&#39;, $Agent)) {
     $os = "Macintosh";
 } elseif (eregi(&#39;PowerPC&#39;, $Agent)) {
     $os = "PowerPC";
 } elseif (eregi(&#39;AIX&#39;, $Agent)) {
     $os = "AIX";
 } elseif (eregi(&#39;HPUX&#39;, $Agent)) {
     $os = "HPUX";
 } elseif (eregi(&#39;NetBSD&#39;, $Agent)) {
     $os = "NetBSD";
 } elseif (eregi(&#39;BSD&#39;, $Agent)) {
     $os = "BSD";
 } elseif (ereg(&#39;OSF1&#39;, $Agent)) {
     $os = "OSF1";
 } elseif (ereg(&#39;IRIX&#39;, $Agent)) {
     $os = "IRIX";
 } elseif (eregi(&#39;FreeBSD&#39;, $Agent)) {
     $os = "FreeBSD";
 }
 if ($os == &#39;&#39;) $os = "Unknown";
 return $os;
 }
 //调用方法$os=os_infor();
Copy after login

49,文件格式类

$mime_types=array(
      &#39;gif&#39;=>&#39;image/gif&#39;,
      &#39;jpg&#39;=>&#39;image/jpeg&#39;,
      &#39;jpeg&#39;=>&#39;image/jpeg&#39;,
      &#39;jpe&#39;=>&#39;image/jpeg&#39;,
      &#39;bmp&#39;=>&#39;image/bmp&#39;,
      &#39;png&#39;=>&#39;image/png&#39;,
      &#39;tif&#39;=>&#39;image/tiff&#39;,
      &#39;tiff&#39;=>&#39;image/tiff&#39;,
      &#39;pict&#39;=>&#39;image/x-pict&#39;,
      &#39;pic&#39;=>&#39;image/x-pict&#39;,
      &#39;pct&#39;=>&#39;image/x-pict&#39;,
      &#39;tif&#39;=>&#39;image/tiff&#39;,
      &#39;tiff&#39;=>&#39;image/tiff&#39;,
      &#39;psd&#39;=>&#39;image/x-photoshop&#39;,

      &#39;swf&#39;=>&#39;application/x-shockwave-flash&#39;,
      &#39;js&#39;=>&#39;application/x-javascript&#39;,
      &#39;pdf&#39;=>&#39;application/pdf&#39;,
      &#39;ps&#39;=>&#39;application/postscript&#39;,
      &#39;eps&#39;=>&#39;application/postscript&#39;,
      &#39;ai&#39;=>&#39;application/postscript&#39;,
      &#39;wmf&#39;=>&#39;application/x-msmetafile&#39;,

      &#39;css&#39;=>&#39;text/css&#39;,
      &#39;htm&#39;=>&#39;text/html&#39;,
      &#39;html&#39;=>&#39;text/html&#39;,
      &#39;txt&#39;=>&#39;text/plain&#39;,
      &#39;xml&#39;=>&#39;text/xml&#39;,
      &#39;wml&#39;=>&#39;text/wml&#39;,
      &#39;wbmp&#39;=>&#39;image/vnd.wap.wbmp&#39;,

      &#39;mid&#39;=>&#39;audio/midi&#39;,
      &#39;wav&#39;=>&#39;audio/wav&#39;,
      &#39;mp3&#39;=>&#39;audio/mpeg&#39;,
      &#39;mp2&#39;=>&#39;audio/mpeg&#39;,

      &#39;avi&#39;=>&#39;video/x-msvideo&#39;,
      &#39;mpeg&#39;=>&#39;video/mpeg&#39;,
      &#39;mpg&#39;=>&#39;video/mpeg&#39;,
      &#39;qt&#39;=>&#39;video/quicktime&#39;,
      &#39;mov&#39;=>&#39;video/quicktime&#39;,

      &#39;lha&#39;=>&#39;application/x-lha&#39;,
      &#39;lzh&#39;=>&#39;application/x-lha&#39;,
      &#39;z&#39;=>&#39;application/x-compress&#39;,
      &#39;gtar&#39;=>&#39;application/x-gtar&#39;,
      &#39;gz&#39;=>&#39;application/x-gzip&#39;,
      &#39;gzip&#39;=>&#39;application/x-gzip&#39;,
      &#39;tgz&#39;=>&#39;application/x-gzip&#39;,
      &#39;tar&#39;=>&#39;application/x-tar&#39;,
      &#39;bz2&#39;=>&#39;application/bzip2&#39;,
      &#39;zip&#39;=>&#39;application/zip&#39;,
      &#39;arj&#39;=>&#39;application/x-arj&#39;,
      &#39;rar&#39;=>&#39;application/x-rar-compressed&#39;,

      &#39;hqx&#39;=>&#39;application/mac-binhex40&#39;,
      &#39;sit&#39;=>&#39;application/x-stuffit&#39;,
      &#39;bin&#39;=>&#39;application/x-macbinary&#39;,

      &#39;uu&#39;=>&#39;text/x-uuencode&#39;,
      &#39;uue&#39;=>&#39;text/x-uuencode&#39;,

      &#39;latex&#39;=>&#39;application/x-latex&#39;,
      &#39;ltx&#39;=>&#39;application/x-latex&#39;,
      &#39;tcl&#39;=>&#39;application/x-tcl&#39;,

      &#39;pgp&#39;=>&#39;application/pgp&#39;,
      &#39;asc&#39;=>&#39;application/pgp&#39;,
      &#39;exe&#39;=>&#39;application/x-msdownload&#39;,
      &#39;doc&#39;=>&#39;application/msword&#39;,
      &#39;rtf&#39;=>&#39;application/rtf&#39;,
      &#39;xls&#39;=>&#39;application/vnd.ms-excel&#39;,
      &#39;ppt&#39;=>&#39;application/vnd.ms-powerpoint&#39;,
      &#39;mdb&#39;=>&#39;application/x-msaccess&#39;,
      &#39;wri&#39;=>&#39;application/x-mswrite&#39;,
      );
Copy after login

50.php生成excel文档

 <?php
     header("Content-type:application/vnd.ms-excel");
     header("Content-Disposition:filename=test.xls");
     echo"test1\t";
     echo"test2\t\n";
     echo"test1\t";
     echo"test2\t\n";
     echo"test1\t";
     echo"test2\t\n";
     echo"test1\t";
     echo"test2\t\n";
     echo"test1\t";
     echo"test2\t\n";
     echo"test1\t";
     echo"test2\t\n";
 ?>

 //改动相应文件头就可以输出.doc.xls等文件格式了
Copy after login

相关推荐:

PHP代码样式风格规范分享

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

The above is the detailed content of Summary of fifty skills for PHP code writing standards (recommended). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template