分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

PHP规范小技巧,来自网络(整理,自得)

发布时间:2023-09-06 02:05责任编辑:熊小新关键词:PHP

---恢复内容开始---

名侦探系列之 50个高质量的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, 不能直接输出如à a等.$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,由始至终使用单一数据库连接

名侦探系列之 50个高质量的PHP代码小技巧 (后篇)

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

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

3,在数据库中保存session

4,避免使用全局变量

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

5,在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>

6,永远不要將 error_reporting 设为 0

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

7,注意平台体系结构

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

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

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

9,使用扩展库 <重要>

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

10,使用MVC框架

11,时常看看 phpbench

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

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

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

13,使用Request Global Array抓取数据

$action = isset($_REQUEST[‘action‘]) ? $_REQUEST[‘action‘] : 0;

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

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

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

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

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

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

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

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

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

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

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

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

23,获取访问者浏览器

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();直接返回结果

24.获取访问者操作系统

 <?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();

25,文件格式类

$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‘, ?????);

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规范小技巧,来自网络(整理,自得)

原文地址:https://www.cnblogs.com/gaokcl/p/9365249.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved