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
2,不要直接使用 require, include, includeonce, requiredonce
$path = root . '/lib/' . $class_name . '.php');require_once( $path );* if(file_exists($path)){ require_once( $path ); }
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"; }}
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){//systemif (function_exists('system')) { ob_start(); // 打开缓冲区 system($command, $return_var); $output = ob_get_contents(); ob_end_clean(); // 清空(擦除)缓冲区并关闭输出缓冲} //passthruelse if (function_exists('passthru')) { ob_start(); passthru($command, $return_var); $output = ob_get_contents(); ob_end_clean();} //execelse if (function_exists('exec')) { exec($command, $output, $return_var); $output = implode("\n", $output);} //shell_execelse 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,灵活编写函数(判断是否是数组来编写逻辑)
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));
6,有意忽略php关闭标签
like: <?php ......................
7, 在某地方收集所有输入, 一次输出给浏览器 <重点>
你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean
8,发送正确的mime类型头信息, 如果输出非html内容的话. <重点>
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response><code>0</code></response>";//send xml dataheader("content-type: text/xml"); //注意header头部echo $xml;
9,为mysql连接设置正确的字符编码
mysqli_set_charset(utf8);
10,使用 htmlentities 设置正确的编码选项 <重点>
php5.4前, 字符的默认编码是iso-8859-1, 不能直接输出如à â等.$value = htmlentities($this->value , ent_quotes , charset);php5.4后, 默认编码为utf-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍要留意编码问题.
11,不要在应用中使用gzip压缩输出, 让apache处理 <重点>
使用apache的mod_gzip/mod_deflate 模块压缩内容. 开启就行了。用途:压缩和解压缩swf文件的代码等,php的zip扩展也行
12,使用json_encode输出动态javascript内容 而不是 echo
13,写文件前, 检查目录写权限
linux系统is_readable($file_path)is_writable($file_path)
14,更改应用创建的文件权限
chmod("/somedir/somefile", 0755);
15,不要依赖submit按钮值来检查表单提交行为
if( $_server['request_method'] == 'post' and isset($_post['submit']) ){ //save the things}
16,为函数内总具有相同值的变量定义成静态变量
static $sync_delay = null;
17,不要直接使用 $_session 变量
不同的应用之前加上 不同的 前缀
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();
19,bunch of silly tips
>> 使用echo取代print >> 使用str_replace取代preg_replace, 除非你绝对需要 >> 不要使用 short tag >> 简单字符串用单引号取代双引号 >> head重定向后记得使用exit >> 不要在循环中调用函数 >> isset比strlen快 >> 始中如一的格式化代码 >> 不要删除循环或者if-else的括号
20,使用array_map快速处理数组
$arr = array_map('trim' , $string);
21,使用 php filter 验证数据 <重点> 可以尝试
22,强制类型检查: intval (int) (string)......
23, 如果需要,使用profiler( 优化php代码 ) 如 xdebug
24,小心处理大数组
确保通过引用传递, 或存储在类变量中:$a = get_large_array();pass_to_function(&$a); // 之后unset掉 释放资源
25,由始至终使用单一数据库连接
26,避免直接写sql, 抽象之;自己封装函数数组,注意转义
27,將数据库生成的内容缓存到静态文件中
28,在数据库中保存session
29,避免使用全局变量
>> 使用 defines/constants >> 使用函数获取值 >> 使用类并通过$this访问
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>
31,永远不要將 error_reporting 设为 0
error_reporting(~e_warning & ~e_notice & ~e_strict);
32,注意平台体系结构
integer在32位和64位体系结构中长度是不同的. 因此某些函数如 strtotime 的行为会不同.
33,不要过分依赖 settimelimit() <重要>
注意任何外部的执行, 如系统调用,socket操作, 数据库操作等, 就不在set_time_limits的控制之下* 一个php脚本通过crontab每5分钟执行一次* sleep函数暂停的时间也是不计入脚本的执行时间的
9,使用扩展库 <重要>
>> mpdf — 能通过html生成pdf文档 >> phpexcel — 读写excel >> phpmailer — 轻松处理发送包含附近的邮件 >> pchart — 使用php生成报表
34,使用mvc框架
35,时常看看 phpbench
可以 php基本操作的基准测试结果,一般php框架 多是有的,具体看文档
36,如何正确的创建一个网站的index页面
学习一种更高效的方式来实现php编程,可以采用“index.php?page=home”模式如在ci中,可以通过 .htaccess /apache/nginx 的配置隐藏index.php
37,使用request global array抓取数据
$action = isset($_request['action']) ? $_request['action'] : 0;
38,利用var_dump进行php代码调试
39,php处理代码逻辑,smarty处理展现层
php原生自带的smarty渲染模板,laravel框架中是 balde模板(同理)
40,的确需要使用全局数值时,创建一个config文件
41,如果未定义,禁止访问! (仿造java等编译语言,php是弱类型的脚本语言的缘故)
like define('wer',1);在其他页面调用时会 if (!defined('wer')) die('access denied');
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\">";
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();直接返回结果
48.获取访问者操作系统
<?php functionosinfo(){ $os = ""; $agent = $globals["http_user_agent"]; if (eregi('win', $agent) && strpos($agent, '95')) { $os = "windows95"; } elseif (eregi('win9x', $agent) && strpos($agent, '4.90')) { $os = "windowsme"; } elseif (eregi('win', $agent) && ereg('98', $agent)) { $os = "windows98"; } elseif (eregi('win', $agent) && eregi('nt5\.0', $agent)) { $os = "windows2000"; } elseif (eregi('win', $agent) && eregi('nt', $agent)) { $os = "windowsnt"; } elseif (eregi('win', $agent) && eregi('nt5\.1', $agent)) { $os = "windowsxp"; } elseif (eregi('win', $agent) && ereg('32', $agent)) { $os = "windows32"; } elseif (eregi('linux', $agent)) { $os = "linux"; } elseif (eregi('unix', $agent)) { $os = "unix"; } elseif (eregi('sun', $agent) && eregi('os', $agent)) { $os = "sunos"; } elseif (eregi('ibm', $agent) && eregi('os', $agent)) { $os = "ibmos/2"; } elseif (eregi('mac', $agent) && eregi('pc', $agent)) { $os = "macintosh"; } elseif (eregi('powerpc', $agent)) { $os = "powerpc"; } elseif (eregi('aix', $agent)) { $os = "aix"; } elseif (eregi('hpux', $agent)) { $os = "hpux"; } elseif (eregi('netbsd', $agent)) { $os = "netbsd"; } elseif (eregi('bsd', $agent)) { $os = "bsd"; } elseif (ereg('osf1', $agent)) { $os = "osf1"; } elseif (ereg('irix', $agent)) { $os = "irix"; } elseif (eregi('freebsd', $agent)) { $os = "freebsd"; } if ($os == '') $os = "unknown"; return $os; } //调用方法$os=os_infor();
49,文件格式类
$mime_types=array( 'gif'=>'image/gif', 'jpg'=>'image/jpeg', 'jpeg'=>'image/jpeg', 'jpe'=>'image/jpeg', 'bmp'=>'image/bmp', 'png'=>'image/png', 'tif'=>'image/tiff', 'tiff'=>'image/tiff', 'pict'=>'image/x-pict', 'pic'=>'image/x-pict', 'pct'=>'image/x-pict', 'tif'=>'image/tiff', 'tiff'=>'image/tiff', 'psd'=>'image/x-photoshop', 'swf'=>'application/x-shockwave-flash', 'js'=>'application/x-javascript', 'pdf'=>'application/pdf', 'ps'=>'application/postscript', 'eps'=>'application/postscript', 'ai'=>'application/postscript', 'wmf'=>'application/x-msmetafile', 'css'=>'text/css', 'htm'=>'text/html', 'html'=>'text/html', 'txt'=>'text/plain', 'xml'=>'text/xml', 'wml'=>'text/wml', 'wbmp'=>'image/vnd.wap.wbmp', 'mid'=>'audio/midi', 'wav'=>'audio/wav', 'mp3'=>'audio/mpeg', 'mp2'=>'audio/mpeg', 'avi'=>'video/x-msvideo', 'mpeg'=>'video/mpeg', 'mpg'=>'video/mpeg', 'qt'=>'video/quicktime', 'mov'=>'video/quicktime', 'lha'=>'application/x-lha', 'lzh'=>'application/x-lha', 'z'=>'application/x-compress', 'gtar'=>'application/x-gtar', 'gz'=>'application/x-gzip', 'gzip'=>'application/x-gzip', 'tgz'=>'application/x-gzip', 'tar'=>'application/x-tar', 'bz2'=>'application/bzip2', 'zip'=>'application/zip', 'arj'=>'application/x-arj', 'rar'=>'application/x-rar-compressed', 'hqx'=>'application/mac-binhex40', 'sit'=>'application/x-stuffit', 'bin'=>'application/x-macbinary', 'uu'=>'text/x-uuencode', 'uue'=>'text/x-uuencode', 'latex'=>'application/x-latex', 'ltx'=>'application/x-latex', 'tcl'=>'application/x-tcl', 'pgp'=>'application/pgp', 'asc'=>'application/pgp', 'exe'=>'application/x-msdownload', 'doc'=>'application/msword', 'rtf'=>'application/rtf', 'xls'=>'application/vnd.ms-excel', 'ppt'=>'application/vnd.ms-powerpoint', 'mdb'=>'application/x-msaccess', 'wri'=>'application/x-mswrite', );
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等文件格式了
相关推荐:
php代码样式风格规范分享
你必须了解的10个编程的技巧
以上就是五十个php代码编写规范的技巧总结(推荐)的详细内容。