---restore content starts---
Detective series of 50 high-quality PHP code tips (previous article)
1, use absolute path, facilitate the migration of code:
define(‘ROOT‘ , pathinfo(__FILE__, PATHINFO_DIRNAME)); require_once(ROOT . ‘../../lib/some_class.php‘); * PATHINFO_DIRNAME 只返回 dirname * PATHINFO_BASENAME 只返回 basename * PATHINFO_EXTENSION 只返回 extension
2, do not use require directly, include, includeonce, requiredonce
$path = ROOT . ‘/lib/‘ . $class_name . ‘.php‘);require_once( $path );* if(file_exists($path)){ require_once( $path ); }
3. Keep Debug code for app
在开发环境中, 我们打印数据库查询语句, 转存有问题的变量值, 而一旦问题解决, 我们注释或删除它们. 然而更好的做法是保留调试代码。在开发环境中, 你可以:* 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, execute commands using a function that can be cross-platform
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, flexible writing function (judging whether it is an array to write logic)
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, intentionally ignoring PHP close tag
like: <?php ......................
7. Collect all inputs in one place, one output to browser < focus >
你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean
8, send the correct MIME type header information if the output is non-HTML content. < focus >
$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. Set the correct character encoding for MySQL connection
mysqli_set_charset(UTF8);
10. Use Htmlentities to set the correct encoding options < focus >
php5.4前, 字符的默认编码是ISO-8859-1, 不能直接输出如à a等.$value = htmlentities($this->value , ENT_QUOTES , CHARSET);php5.4后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍要留意编码问题.
11, do not use gzip compression output in the app, let Apache handle < focus >
使用apache的mod_gzip/mod_deflate 模块压缩内容. 开启就行了。用途:压缩和解压缩swf文件的代码等,PHP的zip扩展也行
12, use Json_encode to output dynamic JavaScript content instead of Echo
13, check the directory write permission before writing the file
linux系统is_readable($file_path)is_writable($file_path)
14. Change the file permissions created by the app
chmod("/somedir/somefile", 0755);
15, do not rely on the Submit button value to check the form submission behavior
if( $_SERVER[‘REQUEST_METHOD‘] == ‘POST‘ and isset($_POST[‘submit‘]) ){ //Save the things}
16, define static variables for variables that have the same value in the function
static $sync_delay = null;
17, do not use the $_session variable directly
不同的应用之前加上 不同的 前缀
18, encapsulate the tool function into the class (same class maintains multiple versions without causing a conflict)
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快 >> 始中如一的格式化代码 >>
20, using ARRAY_MAP to quickly process arrays
$arr = array_map(‘trim‘ , $string);
21, use PHP filter to verify data < focus > can try
22, forcing type checking: intval (int) (string) ...
23, if required, use Profiler (optimized PHP code) such as Xdebug
24, handle large arrays with care
确保通过引用传递, 或存储在类变量中:$a = get_large_array();pass_to_function(&$a); // 之后unset掉 释放资源
25, from start to finish using a single database connection
Detective series of 50 high-quality PHP code tips (later)
1, avoid directly writing SQL, abstract; wrap the function array yourself, note escape
2. Cache database-generated content in a static file
3, save session in database
4, avoid using global variables
>> 使用 defines/constants >> 使用函数获取值 >> 使用类并通过$this访问
5, use base tag in head
> 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, never set the error_reporting to 0
error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
7, pay attention to platform architecture
8, do not rely toomuch on set time limit () < important >
注意任何外部的执行, 如系统调用,socket操作, 数据库操作等, 就不在set_time_limits的控制之下* 一个php脚本通过crontab每5分钟执行一次* sleep函数暂停的时间也是不计入脚本的执行时间的
9, using the extension library < important >
>> mPDF — 能通过html生成pdf文档 >> PHPExcel — 读写excel >> PhpMailer — 轻松处理发送包含附近的邮件 >> pChart — 使用php生成报表
10, using the MVC framework
11, often see Phpbench
可以 php基本操作的基准测试结果,一般PHP框架 多是有的,具体看文档
12, how to create the index page of a website correctly
学习一种更高效的方式来实现PHP编程,可以采用“index.php?page=home”模式如在CI中,可以通过 .htaccess /apache/nginx 的配置隐藏index.php
13. Fetching data using the request Global array
$action = isset($_REQUEST[‘action‘]) ? $_REQUEST[‘action‘] : 0;
14, debugging PHP code with Var_dump
15,php Process code logic, Smarty processing presentation layer
PHP原生自带的Smarty渲染模板,laravel框架中是 balde模板(同理)
16, it is necessary to create a config file when using global values
17, if not defined, access is forbidden! (Imitation of Java and other compiled languages, PHP is a weak type of scripting language for the sake of)
like define(‘wer‘,1);在其他页面调用时会 if (!defined(‘wer‘)) die(‘Access Denied‘);
18, create a database Class (PHP framework is generally integrated, but when the package is native, you can refer to)
19, a PHP file processing input, a class.php file processing specific functions
20, understand your SQL statement, and always review it (Sanitize)
21, when you only need one object, use Singleton mode (three private and one public)
22, about PHP Redirect method one: header ("Location:index.php");
// 方法二 会引发浏览器的安全机制,不允许弹窗弹出 方法二:echo"<script>window.location=\"$PHP_SELF\";</script>"; 方法三:echo"<METAHTTP-EQUIV=\"Refresh\"CONTENT=\"0;URL=index.php\">";
23, Get Visitor browser
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;} Call Method $browser=browseinfo (); return results directly
24. Get the visitor's operating system
<?php Functionosinfo () {$os = ""; $Agent = $GLOBALS ["Http_user_agent"]; if (' Win ', $Agent) && strpos ($Agent, ' eregi ') {$os = "Windows95";} elseif (Eregi (' Win9x ', $Agent) && Amp 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 ', $Agen T) && eregi (' NT ', $Agent)) {$os = "windowsnt";} elseif (Eregi (' win ', $Agent) && eregi (' nt5\.1 ', $Age NT) {$os = "windowsxp";} elseif (Eregi (' win ', $Agent) && ereg (' + ', $Agent)) {$os = "Windows32";} els EIF (eregi (' Linux ', $Agent)) {$os = "Linux";} elseif (Eregi (' Unix ', $Agent)} {$os = "Unix";} elseif (' Su n ', $Agent) && eregi (' OS ', $Agent)) {$os = "SunOS";} elseif (Eregi (' IBM ', $Agent) && eregi (' OS '), $Ag ENT) {$os = "IBMOS/2";} elseif (Eregi (' MAC ', $Agent) && eregi (' PC ', $Agent)) {$os = "Macintosh";} elseif (Eregi (' PowerPC ', $Agent)) {$os = "Pow ErPC "; } elseif (Eregi (' Aix ', $Agent)) {$os = "Aix";} elseif (Eregi (' HPUX ', $Agent)) {$os = "HPUX";} elseif (' N Etbsd ', $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; }//Call method $os=os_infor ();
25, File format class
$mime _types=array (' gif ' = ' image/gif ', ' jpg ' = ' image/jpeg ', ' jpeg ' = ' image/jpeg ', ' jpe ' and ' = ' Image/jpeg ', ' bmp ' = ' image/bmp ', ' png ' = ' image/png ', ' tif ' = ' image/tiff ', ' tiff ' = ' image/t ' Iff ', ' 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 ', ' E ps ' = ' 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 ' = ' a ' Udio/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 ' and ' appli ' Cation/x-tar ', ' bz2 ' = ' application/bzip2 ', ' zip ' = ' application/zip ', ' arj ' = ' Application/x-arj ', ' rar ' = ' application/x-rar-compressed ', ' hqx ' = ' application/mac-binhex40 ', ' sit ' and ' = ' application/x-stu Ffit ', ' 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 ' =& gt; ' Application/rtf ', ' xls ' = ' application/vnd.ms-excel ', ' ppt ' = ' application/vnd.ms-powerpoint ', ' MDB ' =&G t; ' Application/x-msaccess ', ' wri ' = ' application/x-mswrite ',);
PHP generates Excel documents
<?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";
---restore content ends---
PHP specification tips, from the network (collation, complacent)