PHP Code writing specifications in the actual project development of PHP is very important, after all, PHP code can save a lot of unnecessary bug check, the following article I give you to share 50 PHP code writing specifications of the skills.
1, use absolute path, facilitate the migration of code:
Define (' ROOT ', PathInfo (__file__, pathinfo_dirname)); Require_once (ROOT. '.. /.. /lib/some_class.php '); * Pathinfo_dirname only return DIRNAME * pathinfo_basename only return BASENAME * pathinfo_extension only return 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
In the development environment, we print the database query statements, dump the problematic variable values, and once the problem is resolved, we annotate or delete them. However, a better practice is to keep the debug code. In the development environment, you can: * Define (' environment ', ' development '); if (! $db->query ($query) { if (environment = = ' development ') { echo "$query failed"; } else {echo "Dat Abase error. Please contact administrator "; } }* in the server, you can: define (' Environment ', ' production '); if (! $db->query ($query) { if (environment = = ' development ') c7/>{ 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 these 4 functions can be used to execute system commands/** * 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 (); Open buffer System ($command, $return _var); $output = Ob_get_contents (); Ob_end_clean (); Empty (erase) buffer and close output buffer}//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 exe Cution not possible on the 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 >
You can store them in local variables of a function, or you can use Ob_start and 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 "); Notice the head of the 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 >
Before php5.4, the character's default encoding is iso-8859-1 and cannot be directly output such as àâ. $value = Htmlentities ($this->value, Ent_quotes, CHARSET);p hp5.4, The default encoding is UTF-8, which solves many problems. But if your app is multilingual, be aware of the coding problem.
11, do not use gzip compression output in the app, let Apache handle < focus >
Use Apache's Mod_gzip/mod_deflate module to compress content. Turn on the line. Purpose: Compress and decompress SWF file code and so on, php zip extension line
12, use Json_encode to output dynamic JavaScript content instead of Echo
13, check the directory write permission before writing the file
Linux system 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
Different applications before adding different prefixes
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 Utilit Y_c () {}} $a = Utility::utility_a (); $b = Utility::utility_b ();
19,bunch of Silly tips
>> use echo instead of print >> use str_replace instead of preg_replace, unless you absolutely need >> do not use short tag >> simple string with single quotation mark instead of double quotation mark >> head redirect remember to use Exit >> do not call function in loop >> isset faster than strlen >> Formatting code as in the beginning >> do not delete loops or if-else parentheses
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
Ensure that it is passed by reference, or stored in a class variable: $a = Get_large_array ();p ass_to_function (& $a); And then unset out the resources.
25, from start to finish using a single database connection
26, avoid directly writing SQL, abstract; wrap the function array yourself, note escape
27. Cache database-generated content in a static file
28, save session in database
29, avoid using global variables
>> using defines/constants >> using functions to get values >> using classes and accessing through $this
30, use base tag in head
> www.domain.com/store/home.php > Www.domain.com/store/products/ipad.php Change to://Base route <base href= " Http://www.domain.com/store/"><a href=" home.php ">home</a><a href=" products/ipad.php ">ipad </a>
31, never set the error_reporting to 0
Error_reporting (~e_warning & ~e_notice & ~e_strict);
32, pay attention to platform architecture
Integers are different in length in 32-bit and 64-bit architectures. Therefore, some functions, such as strtotime, behave differently.
33, do not rely toomuch on set time limit () < important >
Note that any external execution, such as system calls, socket operations, database operations, etc., is not under the control of Set_time_limits * A PHP script executes once every 5 minutes by crontab * The time of sleep function pauses is not counted as the execution time of the script.
9, using the extension library < important >
>> mpdf-can generate PDF documents via HTML >> phpexcel-Read and write Excel >> phpmailer-easily handle sending messages containing nearby >> pchart-using PHP to generate reports
34, using the MVC framework
35, often see Phpbench
PHP basic operations can be a benchmark test results, the general PHP framework is a lot of, specific look at the document
36, how to create the index page of a website correctly
Learn a more efficient way to implement PHP programming, you can use the "index.php?page=home" mode, such as in CI, can be hidden through the configuration of the. htaccess/apache/nginx index.php
37. Fetching data using the request Global array
$action = Isset ($_request[' action ')? $_request[' action ']: 0;
38, debugging PHP code with Var_dump
39,php Process code logic, Smarty processing presentation layer
PHP native Smarty rendering template, Laravel frame is Balde template (same as)
40, it is necessary to create a config file when using global values
41, 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); When called on other pages, the if (!defined (' wer ')) die (' Access Denied ');
42, create a Database Class (PHP framework is generally integrated, but when the package is native, you can refer to)
43, a PHP file processing input, a class.php file processing specific functions
44, understand your SQL statement, and always review it (Sanitize)
45, when you only need one object, use Singleton mode (three private and one public)
46, about PHP Redirect method one: header ("Location:index.php");
Method Two will trigger the browser security mechanism, do not allow Pop popup method two: Echo "<script>window.location=\" $PHP _self\ ";</script>"; Method Three: Echo "<metahttp-equiv=\" refresh\ "content=\" 0; Url=index.php\ ">";
47, 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
48. Get visitor 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 ();
49, 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 ',);
50.php Generating 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"; echo "test2\t\n";?>//change the corresponding file header to output. Doc.xls and other file formats