PHP coding framework

Source: Internet
Author: User
Tags coding standards php coding standards
PHP coding standards are becoming more and more important in the compilation process of PHP. today, I saw articles written by my predecessors on the Internet. Original article address: Coding Specification for PHP development
In the compilation process of PHP, the importance of standardization is becoming more and more important. today, I saw articles written by my predecessors on the Internet. Original address:

1. writing purpose
This specification is specified to better 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 will follow the PEAR specifications and basically adopt the specifications specified by PEAR, and 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 naming rules
Extracted include files with common functions. the file suffix is named ". inc", indicating that this is an include file.
If multiple. inc files need to contain multiple pages, encapsulate all. inc files in one file. you only need to package A. inc file on the page.
Xxx_comm.. inc

Encapsulate the above files in the xxx. basic. inc file.
Require_once (" ");
Require_once (" ");
Require_once (" ");
Require_once (" ");

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, files that contain files do not need to be directly exposed to users. Therefore, they should be placed in a directory inaccessible to the Web Server to avoid configuration leakage.

3.2 Security Rules
See the product security checklist.

Input and output
Check whether HTML code is filtered.
Possible problems: malicious HTML code may cause cookie theft, malicious login forms, and website destruction.
Check whether escape is performed before the variable is used for database operations.
Possible problems: if a string variable to write a query statement contains some special characters, such as quotation marks (', ") or semicolons (;) operations beyond expectation may be performed.
Recommended method: Use mysql_escape_string () or implement functions similar to this function.
Check validity of input values
Possible problems: abnormal values may cause problems. 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.
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 cookie usage and processing of user data
Possible problems: incorrect cookie usage may cause user data leakage
Access control
Consider adding access control to products used internally or products used by partners.
Make sure that the user's confidential information is not recorded in the log (for example, the user's password)
Ensures complete user access records for key user operations
Use https for sensitive data transmission.

3.3 some PHP rules
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.
Put the actual operation in the referenced file. Place the referenced file in a directory that cannot be directly browsed.

3.4 Other processing rules

3.4.1 escape input parameter values
When receiving parameters on the page, you need to perform SQL operations. at this time, you need to escape them. pay special attention ";".
For example: $ a = "Let's go ";
$ SQL = "Insert into tmp (col) values ('$ ')";
Uncertainty in this case.

3.4.2 large HTML text operations
Most of the time, you need to store a large part of HTML text for use on the page, such as customizing the 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 naming rules
Developing a unified naming convention is very important for project development. it not only helps programmers develop good habits, but also increases program readability, portability, and reusability, it can also improve the efficiency of project development.

4.1.1 Variable naming
Variable naming rules include common variables, static variables, local variables, global variables, and Session variables. common variables
Naming common variables follows the following rules:
A. all letters are in lower case;
B. for a variable that uses multiple words, use '_' as the interval of each word.
For example: $ base_dir, $ red_rose_price, etc. static variables
Static variable naming rules are as follows:
A. static variables start with lowercase s;
B. all letters in static variables are in lower case;
C. variable names composed of multiple words use '_' as the interval of each word.
Example: $ s_base_dir, $ s_red_rose_prise, etc. local variables
The naming of local variables follows the following rules:
A. all letters are in lower case;
B. The variable starts;
C. The local variable name consisting of multiple words uses '_' as the interval between each word.
Example: $ _ base_dir and $ _ red_rose_price. global variables
Global variables should have the prefix 'g'. it is very important to know the scope of a variable.
For example
Global $ gLOG_LEVEL;
Global $ gLOG_PATH; global constants
Global variable naming rules are as follows:
A. uppercase letters are used for all letters.
B. use '_' as the interval between multiple words in the global variable.
Example: $ BASE_DIR, $ RED_ROSE_PRICE, etc. session variable
The session variable naming rules are as follows:
A. uppercase letters are used for all letters;
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
Class naming in php follows the following rules:
A. Start with an uppercase letter;
B. variable names composed of multiple words. there is no interval between words. each word is capitalized.
Example: class MyClass or class DbOracle.

4.1.3 methods or functions
The method or function naming rules are as follows:
A. lowercase letters;
B. There is no interval between multiple words. except the first word, the first letter of other words is capitalized.
Example: function myFunction () or function myDbOracle.

4.1.4 acronyms
When the variable name or other names encounter acronyms, refer to the specific naming rules, instead of using the original method of all uppercase words.
Example: function myPear (not myPEAR) functio getHtmlSource (not getHTMLSource ).

4.1.5 database table name
Database table names follow the following rules:
A. table names all use lower-case letters;
B. use _ t to end a common data table;
C. for a view, end with _ v;
D. use _ interval for table names composed of multiple words;
Example: user_info_t and book_store_v

4.1.6 database fields
The database field naming rules are as follows:
A. use lower-case letters;
B. use the _ interval between multiple words.
Example: user_name, rose_price, etc.

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

4.2.1 Code indent
When writing code, you must pay attention to the code indent rules. The Code indent rules are as follows:
A. Use four spaces as indentation instead of tab indentation (you can set ultraedit in advance)
For ($ I = 0; $ I <$ count; $ I ++)
Echo "test ";

4.2.2 braces {} writing rules
Structure control code writing in a program, such as if, for, while, and switch structures. braces have two traditional writing habits:
A. {directly follows the control statement without line breaks, as shown in figure
For ($ I = 0; $ I <$ count; $ I ++ ){
Echo "test ";
B. {the next row in the control statement, as shown in figure
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 specifications and the phpdoc implementation documentation, therefore, the above two methods can be used according to your habits, but only one of them must be used in the same program to avoid inconvenience in reading.

4.2.3 parentheses (), functions, and keywords
Parentheses, keywords, and functions follow the following rules:
A. Do not enclose parentheses with keywords. 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
The = symbol in the program follows the following rules:
A. leave a space on both sides of the = symbol, such as $ a = $ B and if ($ a = $ B;
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 writing
Write the control structure according to the following rules:
A. in the if condition judgment, if the constant judgment condition is used, place the constant on the left side 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;
B. The default block must exist in the switch structure;
C. be cautious with the use of continue and break in the loop of for and wiile to avoid problems similar to goto;

4.2.6 constructors
To write constructors in a class, follow these rules:
A. There cannot be too many actual operations in the constructor. at most, they are used to initialize some values and variables;
B. You cannot return false or error in the constructor because of the operation, because errors cannot be returned when an object is declared and instantiated;

4.2.7 The statement breaks the line. each line must be within 80 characters.
In code writing, follow the following principles:
A. try to ensure that one line of the program statement is a line, rather than making a line of statement too long to generate a line;
B. try not to make the code of a line too long. generally, it should be within 80 characters;
C. If a line of code is too long, use a method similar to. = to cut the line of writing;
D. Do not write SQL statements in the function to execute Database SQL statements. Instead, define SQL statements with variables and then call the defined variables in the function that executes the operation;
$ 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 has no meaning in three months. For example:

If (22 = $ foo)
Start_thermo_nuclear_war ();
Else if (19 = $ foo)
Refund_lotso_money ();
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 ");

Start_thermo_nuclear_war ();
Else if (WE_GOOFED ==$ foo)
Refund_lotso_money ();
Else if (THEY_DIDNT_PAY = $ foo)
Infinite_loop ();
Happy_days_ I _know_why_im_here ();
4.2.9 true/false and 0/1
Follow the following rules:
A. 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 true/false judgment;
For example, if (FALSE) is used instead of if ($ a) or if (checka! = $ A) or if (FALSE! = Check ())

4.2.10 Avoid embedded assignment
Avoid the embedded assignment in the following example in the program:
Do not use this method:
While ($! = ($ C = getchar ()))
Process the character

4.2.11 error return detection rules
Check all system call errors unless you want to ignore them.
Define the system error text for each system error message and record the error LOG.

4.3 program annotation
Each program must provide the necessary comments, write the annotation requirements specification, and refer to the annotation requirements provided by PEAR to prepare for generating php documents using phpdoc in the future. The program annotation principles are as follows:
A. except for the annotation block of the file header, the/annotation is not used in other places, but the/**/annotation is used;
B. The content of the comment must be written before the object to be commented on, not in one line or later;

4.3.1 program header comment block
Each program header must have a uniform comment block. The rules are as follows:
A. The description of this program must be included;
B. The author must be included;
C. The written date must be included;
D. The version information must be included;
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;

// + --------------------- +
// | 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:// |
// | If you did not receive a copy of the and are unable to |
// | Obtain it through the world-wide-web, end a note to |
// so we can mail you a immediately. |
// + --------------------- +
// | Authors: Stig Bakken |
// | Tomas V. V. Cox |
// |
// + --------------------- +
// $ Id: Common. php, v 2001/11/13 01:26:48 ssb Exp $
4.3.2 class comments
Class annotations use the following reference example:

* @ Purpose:
* Database access class. ODBC is used as the Universal Access interface.
* @ Package Name: Database
* @ Author: Forrest Gump
* @ Modifications:
* No20020523-100:
* The second and third positions of the odbc_fetch_into () parameters are swapped.
* John Johnson
* @ See: (reference)
Class Database
4.3.3 Comments of functions and methods
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 the mixed query (result set object)
Function ($ queryStr, $ username)
4.3.4 comment on variables or statements
Annotations of variables or statements in a program follow the following principles:
A. write it in the first line of a variable or statement instead of the same line or later;
B./**/is used for annotations;
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.

* @ Purpose:
* Database connection username
* @ Attribute/Variable Name: db_user_name
* @ Type: string
Var db_user_name;

4.4 Other specifications (recommended)

4.4.1 php code mark
All php code blocks are marked

4.4.2 program file name and directory name
The program file name and directory name are named in meaningful English. do not use pinyin or meaningless letters. at the same time, lowercase letters must be used. Separate multiple words.

4.4.3 common file directory structure of PHP projects
We recommend that you use the standard file directory structure when developing a standardized and independent PHP project, which helps improve the rationality of the project's logical structure, corresponding expansion and cooperation, and team development.
A complete and independent PHP project usually has the following file and directory structures:
/Project root directory
/Manage admin file storage directory
/Css file storage directory
/Doc stores project documents
/Images path for storing all image files (in which subdirectories are set up based on the directory structure)
/Scripts client js script storage directory
/Directory for storing all html template files on the tpl website
/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
For projects and applications with low performance requirements, we recommend that you do not directly mix PHP and HTML code to write code, but separate PHP and HTML code, that is, the template is used for processing. On the one hand, it makes the logic structure of the program clearer and facilitates the division of labor in the development process, at the same time, it also provides more convenience to upgrade the version of the Japanese project page.
In some special cases, such as applications with high performance requirements, templates are not recommended.

4.4.5 program logic structure in PHP project development
For PHP project development, we should try to use the idea of OOP for development. especially after PHP5, the object-oriented development function is 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 the 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, such as the first line of isset () for example, the following code:
$ Array = array ();
$ Var = isset ($ array [3])? $ Array [3]: "";

5.2 Reference
References are used in many 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 parameters 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 that $ B = AB (& $ a) cannot be used here;
Echo $ B. "\ n ";
Echo $ a. "\ n ";
In this case, 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 input and output of variables
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.

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: 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.