PHP coding specifications

Source: Internet
Author: User
Tags coding standards php error

Over the years, I have been engaged in PHP and C-related development in Linux and have brought many projects and teams. The following PHP coding specifications based on my experience can be used as examples and references for everyone, select and modify as needed!

(Some of the latest PhP5 specifications may be incomplete and will be updated in the future !)

Directory 1 writing Objective 2 Overall requirements 3 security specifications 3.1 inclusion files 3.1.1 naming rules 3.1.2 storage rules 3.2 security rules 3.3 some PHP rules 3.4 other processing rules 3.4.1 escape input parameter values 3.4.2 large HTML text operations

 

4 coding specification 4.1 naming convention 4.1.1 variable naming 4.1.2 class 4.1.3 method or function 4.1.4 acronym 4.1.5 database table name 4.1.6 database Field 4.2 writing rule 4.2.1 code indent 4.2.2 braces {} writing rule 4.2.3 parentheses () and function, keyword, etc. 4.2.4 = symbol writing 4.2.5 if else swith for while and so on write 4.2.6 class constructor 4.2.7 statement broken line, each line is controlled within 80 characters 4.2.8 not incredible numbers 4.2.9 true/false and 0/1 judgment 4.2.10 avoid embedded assignment 4.2.11 error return detection Rule 4.3 program comment 4.3.1 program header comment block 4.3.2 class comment 4.3.3 comments to functions and methods 4.3.4 comments to variables or statements 4.4 Other Provisions (recommended) 4.4.1 PHP code mark 4.4.2 program file name, directory name 4.4.3 PHP project's common file directory structure 4.4.4 separation of PHP and HTML code 4.4.5 PHP Project Development Program Logic Structure 5 PHP coding in a specific environment special specification 5.1 variable definition 5.2 Reference using 5.3 variable input and output

1. Purpose: To improve the efficiency of the technical department, ensure the effectiveness and rationality of development, and maximize the readability and reusability of program code. The development team can supplement or reduce this specification based on their actual conditions.

2. Overall requirements the php development specifications of the technical department should follow the pear specifications and use the specifications specified by pear to add, modify, or delete some of the Specifications suitable for specific development environments. This specification is only applicable to coding standards during php development. It will not focus on files, directories, databases, and other specifications in PHP development projects. This specification includes naming rules, code indentation rules, control structures, function calls, function definitions, comments, comments containing code, PHP tags, file header comments, CVS tags, URL samples, and constant naming rules.

3. Security specifications

3.1 include files

3.1.1 The naming rule extracts the inclusion files with common functions. The file suffix is named by. Inc, indicating that this is an inclusion file. If there are multiple. the INC file must contain multiple pages. the INC file is encapsulated in a file. You only need to package one file on the page. inc file, for example: xxx_session.inc xxx_comm .. INC xxx_setting.inc mysql_db.inc

Encapsulate the above files in XXX. basic. require_once ("xxx_session.inc") in the inc file; require_once ("xxx_comm.inc"); require_once ("xxx_setting.inc"); require_once ("mysql_db.inc ");

Note: whether to encapsulate a file depends on the situation. If each Inc function is distributed to different pages, it is not recommended to encapsulate it.

3.1.2 storage rules generally include files that do not need to be directly exposed to users. Therefore, they should be placed in a directory inaccessible to the Web server to avoid leakage of configuration information due to configuration problems.

3.2 for security rules, see the product security checklist.

Check whether HTML code is filtered for input and output: If malicious HTML code is entered, the cookie will be stolen and a malicious login form will be generated, whether or not escape may occur before the Website check variable is used for database operations: If a string variable to write a query statement contains some special characters, such as quotation marks (', ") or semicolon (;) may cause operations beyond expectation. Recommended method: Use mysql_escape_string () or implement functions similar to this function. Check the legality of the input value. An abnormal value may cause a problem. If you do not check the input values, illegal or incorrect data will be stored in UDB, other databases, or unexpected program operations will occur. For example, if the program uses the parameter value entered by the user as the file name, malicious input of the system file name will cause damage to the system. Verify the use of cookies and possible problems with processing user data: incorrect use of cookies may cause user data leakage, access control, and internal use of products or products for use by partners, consider adding access control logs to ensure that the user's confidential information is not recorded in the log (for example, the user's password) ensure that the complete user access records are saved for key user operations. HTTPS must be used for sensitive data transmission.

3.3 set register_globals = off (y! PHP has disabled register_globals. If you use y! PHP does not consider this setting.) set error_reporting = e_all (y! PHP default settings), and all errors and warnings must be corrected to put the actual operations in the referenced file. Place the referenced file in a directory that cannot be directly browsed.

3.4 other processing rules

3.4.1 The Escape processing page for input parameter values requires SQL operations to receive parameters. In this case, escape is required. Pay special attention ";". For example, $ A = "Let's go"; $ SQL = "insert into TMP (COL) values ('$ A')"; errors may occur in this case.

3.4.2 When operating large HTML texts, you often need to store a large segment of HTML text for use on pages, such as custom page header and footer. Script flag should be removed to avoid malicious PHP code execution. Convert "<" ">" to ensure the code is complete.

4. coding specifications

4.1 standardized naming is very important for project development. It not only helps programmers develop a good habit, but also increases program readability, portability, and reusability, it can also improve the efficiency of project development.

4.1.1 naming rules for variable names include common variables, static variables, local variables, global variables, and session variables.

4.1.1.1 naming of common variables follows the following rules: A. All letters are in lowercase; B. If a variable uses multiple words, '_' is used as the interval of each word. For example: $ base_dir, $ red_rose_price, etc.

4.1.1.2 static variables follow the following naming rules:. static variables start with lowercase S _; B. all static variables use lower-case letters. C. variable names composed of multiple words use '_' as the interval of each word. Example: $ s_base_dir, $ s_red_rose_prise, etc.

4.1.1.3 naming of local variables follows the following rules:. all letters are in lower case; B. variable starts with '_'; C. the local variable name consisting of multiple words uses '_' as the interval between each word. Example: $ _ base_dir and $ _ red_rose_price.

4.1.1.4 The global variable must have the prefix 'G'. It is very important to know the scope of a variable. For example, global $ glog_level; global $ glog_path;

4.1.1.5 the naming of global variables of global constants follows the rules below: A. All letters use uppercase letters B. The interval between multiple words of global variables is. Example: $ base_dir, $ red_rose_price, etc.

4.1.1.6 the session variable name follows the following rules:. all letters are in uppercase; B. the session variable name starts with's _ '. C. use '_' to separate multiple words. Example: $ s_base_dir, $ s_red_rose_price, etc.

4.1.2 class names in PHP should follow the following rules: a. a. a variable name consisting of multiple words. There is no interval between words. The first letter of each word is capitalized. Example: Class myclass or class dboracle.

4.1.3 The method, function method, or function naming rules are as follows: A. lowercase letters; B. Multiple words do not use an interval. Except the first word, other words are capitalized. Example: function myfunction () or function mydboracle.

4.1.4 when a variable name or other names encounter a scale-in, refer to the specific naming rules, instead of all the original scale-in methods. Example: function mypear (not mypear) functio gethtmlsource (not gethtmlsource ).

4.1.5 database table name naming rules are as follows:. table names all use lower-case letters; B. for common data tables, end with _ t; C. for a view, end with _ v; D. for Table names composed of multiple words, use the _ interval. Example: user_info_t and book_store_v

4.1.6 database field database Field names follow the following rules: A. All use lower case; B. Use _ interval between multiple words. Example: user_name, rose_price, etc.

4.2 writing rules refer to the rules for writing code when writing a PHP program, including indentation, structure control, and other specifications:

4.2.1 code indentation when writing code, you must pay attention to the Code indent rules. We stipulate the code indent rules as follows:. use four spaces as indentation without tab indentation (for ultraedit, you can set it in advance) Example: For ($ I = 0; $ I <$ count; $ I ++) {echo "test ";}

4.2.2 structure control code is written in the program according to the braces {}, such as if, for, while, and switch. The traditional braces have two writing habits:. {directly following the control statement, do not wrap, such as for ($ I = 0; $ I <$ count; $ I ++) {echo "test" ;} B. {In the next row of the control statement, for example, for ($ I = 0; $ I <$ count; $ I ++) {echo "test, A is the method recommended by pear, but in actual writing, this does not affect the program specification and the phpdoc implementation documentation. Therefore, you can use the above two methods according to your habits, however, you must use only one of them in the same program to avoid reading inconvenience.

4.2.3 parentheses (), function, keyword, and other parentheses, keywords, and functions follow the following rules:. do not enclose parentheses and keywords together. Use a space interval, for example, if ($ A <$ B); B. there is no space between the parentheses and the function name. For example, $ test = date ("ymdhis"); C. do not use parentheses in return statements unless necessary. Such as return $;

4.2.4 = symbol writing in the program = symbol writing follows the following rules:. leave a space on both sides of the = symbol, such as $ A = $ B, if ($ A = $ B), and B. in a declarative block or a block that implements the same function, the = sign is used up and down as much as possible. Multiple spaces can be used to maintain alignment on the left, and a space must be left on the right; for example: $ Testa = $ AAA; $ testaa = $ BBB; $ testaaa = $ CCC;

4.2.5 if else swith for while writes the control structure following the following rules:. in the if condition judgment, if the constant judgment condition is used, place the constant on the left of the equal or non-equal sign, for example, if (6 = $ errornum ), because if you miss an equal sign in the equation, the syntax Checker will report an error for you, and you can quickly find the error location. pay more attention to this writing method; B. the switch structure must have default blocks; C. in the loop use of for and wiile, be cautious with the use of continue and break to avoid problems similar to goto;

4.2.6 class constructor if you want to write constructor in the class, you must follow the following rules:. there cannot be too many actual operations in the constructor, and at most some values and variables can be initialized; B. you cannot return false or error in the constructor because of operations, because errors cannot be returned when an object is declared and instantiated;

4.2.7 when a statement is disconnected, each line is controlled to be less than 80 characters in code writing and follows the following principles:. make sure that one line of a Program Statement is one, rather than a line of statement that is too long. B. do not make the code of a line too long. Generally, it must be within 80 characters. C. if a line of code is too long, use a line similar. =. do not write SQL statements in the function to execute Database SQL statements. Instead, define SQL statements with variables and call the Defined variables in the function that executes the operation. For example: $ SQL = "select username, password, address, age, postcode from test_t"; $ SQL. = "where username = 'aaa'"; $ res = mysql_query ($ SQL );

4.2.8 not an incredible number. A naked number used in the source code is an incredible number, because it contains the author, and no one has its meaning within three months. For example:

If (22 = $ Foo) {start_thermo_nuclear_war ();} elseif (19 = $ Foo) {refund_lotso_money ();} else {cry_cause_im_lost ();}

You should use define () to give you a real name for the value of something, rather than a naked number, for example:

Define ("president_went_crazy", "22"); define ("we_goofed", "19"); define ("they_didnt_pay", "16 "); if (Rule = $ Foo) {start_thermo_nuclear_war ();} elseif (we_goofed = $ Foo) {refund_lotso_money ();} elseif (they_didnt_pay = $ Foo) {infinite_loop ();} else {happy_days_ I _know_why_im_here ();}

4.2.9 true/false and 0/1 follow the following rules:. 0/1 cannot be used to replace true/false. in PHP, This is not equal; B. do not use a non-zero expression, variable, or method to directly perform true/false judgment, but use a strict and complete true/false judgment. For example, if ($ A) is not used) or if (checka () and use if (false! = $ A) or if (false! = Check ())

4.2.10 avoid embedded assignment in the program to avoid embedded assignment in the following example: Do not use this method: While ($! = ($ C = getchar () {process the character}

4.2.11 return error detection rules to check all system call error information, unless you want to ignore the error. Define the system error text for each system error message and record the error log.

4.3 program comments each program must provide the necessary comments, write the annotation requirements specification, and refer to the comments requirements provided by pear to prepare for generating PHP documents using phpdoc in the future. The program annotation principles are as follows:. note: Except for the comment block of the file header, the/comment is not used in other places, but the/**/comment is used. B. the comment must be written in front of the commented object, not in one or more lines;

4.3.1 The program header annotation block each program header must have a uniform annotation block. The rules are as follows:. must contain the description of this program; B. must contain the author; C. must contain the writing date; D. must contain version information; E. the project name must be included; F. the file name must be included; G. important usage instructions, such as class call methods and precautions. The reference examples are as follows:

<? PHP // + versions + // | PHP version 4.0 | // + --------------------------------------------------------------- + // | copyright (c) 1997-2001 the PHP Group | // + ------------------------------------------------------- + // | this source file is subject to of the PHP license, | // | that is bundled with this packafile license, and is | // | available at through the world-web at | // | http://www.php.net/license/2_02.txt. | // | if you did not receive a copy of the and are unable to | // | obtain it through the World-Wide-web, end a note to | // | license@php.net so we can mail you a immediately. | // + --------------------------------------------------------- + // | authors: Stig Bakken <ssb@fast.no> | // | Tomas v. v. cox <cox@idecnet.com> | // + ------------------------------------------------------------- + // $ ID: Common. PHP, V 1.8.2.3 2001/11/13 01:26:48 SSB exp $

4.3.2 the annotation of a class uses the following reference example:

/*** @ Purpose: * class to access the database, using ODBC as a universal access interface * @ package name: database * @ Author: Forrest Gump gump@crtvu.edu.cn * @ modifications: * No20020523-100: * The second and third locations of the odbc_fetch_into () parameter change * John Johnson John@crtvu.edu.cn * @ see: (reference) */classdatabase {...... }

4.3.3 comments of functions and methods are written before functions and methods. rules similar to the following example are used:

/*** @ Purpose: * execute a query * @ Method Name: Query () ** @ Param: String $ querystr SQL query string * @ Param: string $ username ** @ Author: Michael Lee ** @ return: Return Value of mixed query (result set object) */function ($ querystr, $ username ){......}

4.3.4 annotations for variables or statements in the program follow the following principles:. written in the first line of a variable or statement, not in the same line or later; B. comments are in the/**/mode. C. each function must contain a comment block. The content includes the function description, input/output parameters, expected return values, and error code definition. D. Complete annotations. E. delete codes that have been commented out, or indicate the special reasons for the codes that have been commented out to be retained in the source code. F. Example:

/*** @ Purpose: * database connection username * @ attribute/variable name: db_user_name * @ Type: string */vardb_user_name;

4.4 Other Specifications (recommended)

4.4.1 Use PHP code to mark all PHP program code blocks

4.4.2 program names, directory names, program names, and directory names are named in meaningful English. lowercase letters are not used, use _ interval between multiple words.

4.4.3 it is recommended that the standard file directory structure be used when developing standard independent PHP projects. This helps improve the rationality of the project's logical structure, and expand and cooperate with each other, and team development. A complete and independent PHP project usually has the following file and directory structures: /Project root directory/manage background management file storage directory/CSS file storage directory/DOC Storage Project Document/images all image file storage path (in which subdirectories are set up according to the directory structure) /scripts client JS Script directory/TPL website all HTML template files directory/error. PHP error handling file (which can be defined in Apache error handling)

The preceding directory structure is a common directory structure. You can consider not to follow it completely based on the specific application conditions, but try to standardize it as much as possible.

4.4.4 separation of PHP and HTML code does not require high performance projects and applications. We recommend that you do not directly mix PHP and HTML code to write code generation, the separation of PHP and HTML code, that is, template-based processing. On the one hand, this makes the logic structure of the program clearer and facilitates the division of labor in the development process, it also provides more convenience for upgrading the version of the project page in the future. In some special cases, such as applications with high performance requirements, templates are not recommended.

4.4.5 The Program Logic Structure in PHP project development should be developed with the idea of OOP as much as possible for PHP project development. Especially after PhP5, the object-oriented development function will be greatly improved. In the PHP project, we suggest writing independent functional modules as function calls as much as possible, corresponding to a whole business logic. We suggest encapsulating them into classes to improve code readability, it can also improve code reusability. For example, we usually encapsulate database interfaces into database classes, which facilitates the migration of platforms. Duplicate code should be made into a public library. (In addition to the situation we encounter on the plug-in product, this product series has many similar products, in order to minimize the installation package size, it is not suitable to make all functions shared by these products into a public library)

5. Special PHP coding specifications in specific environments

5.1 variable definition PHP code writing in XXX environment requires that all variables should be affirmed before use, otherwise there will be an error message. For arrays, when using an uncertain key, for example, determine isset () first and then use it. For example, the following code: $ array = array (); $ Var = isset ($ array [3])? $ Array [3]: "";

5.2 references are often used in programs. In order to share the same memory without additional replication, pay attention to the following situations when referencing in the xxx environment; when a reference is used in the input parameters of a function, you can directly use this variable instead of adding & to the input parameters during the call, the input parameter must also be referenced when the function is defined. For example, the following code: $ A = 1; function AB (& $ var) {$ var ++; return $ var;} $ B = AB ($ A) // Note: $ B = AB (& $ A) cannot be used here; echo $ B. "/N"; echo $. "/N"; at this time, both $ A and $ B are 2;

Special requirements for reference in the xxx environment are derived from PHP. the allow_call_time_pass_reference item in the INI file is set. The public version is on, so that it can be directly added to the variable before calling the function. However, this method has been protested, it may not be supported in future PHP/Zend versions. It is encouraged to specify which parameters are passed by reference in the function declaration. You are encouraged to disable this option (with off, all runtime environments of XXX are off) and confirm that your script is still working normally, to ensure that they can still work in future versions.

5.3 When the input and output of variables are in the xxx environment, strict filtering and legality verification are required for parameters transmitted through the get or POST method on the web, we do not recommend that you use $ _ Get, $ _ post, or $ _ request directly, but use the methods provided by the xxx_yiv module of XXX to obtain and filter data.

Standardized!

Note: The XXX environment mentioned in the Specification refers to the specific development environment of XXX company that xx once worked in!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.