PHP Development Code Track

Source: Internet
Author: User
Tags naming convention php error script tag
Code Specification for PHP development
In the process of writing PHP, more and more feel the importance of standardization, today on the network to see predecessors write articles, special turn to learn. The original address is: http://blog.csdn.net/alexdream/article/details/2213313

1 Purpose of writing
In order to better improve the efficiency of the technical department, to ensure the effectiveness and rationality of development, and to maximize the readability of the program code and reusable, specify this specification. The development team can supplement or reduce this specification according to its own actual situation.

2 overall requirements
The PHP Development Code of the Ministry of Technology will refer to the specifications of pear, and use the specifications specified by pear to add, modify or delete some of the specifications suitable for the specific development environment. This specification is only for the code in PHP development process, for PHP development project files, directories, databases and other aspects of the specification, will not focus on.
This specification contains rules for naming specifications, code indentation rules, control structures, function calls, function definitions, annotations, include code, PHP tags, header comment blocks, CVS tags, url samples, and constant naming in PHP development.

3 Safety Specifications

3.1 Include files

3.1.1 Naming rules
Extract the include file that has a common function, and the file suffix is named by. Inc to indicate that it is an include file.
If you have multiple. inc files that need to contain multiple pages, enclose all the. inc files in a single file, and only one. inc file is required for the page.
such as: Xxx_session.inc
Xxx_comm. Inc
Xxx_setting.inc
Mysql_db.inc

Put the above file in a way, encapsulated in the Xxx.basic.inc file
Require_once ("Xxx_session.inc");
Require_once ("Xxx_comm.inc");
Require_once ("Xxx_setting.inc");
Require_once ("Mysql_db.inc");

Note: If you need to encapsulate to a file, depending on the situation, if each inc's functionality is spread across different pages, it is not recommended to encapsulate it.

3.1.2 Storage Rules
The generic include file does not need to be exposed directly to the user, so it should be placed in a directory that is not accessible to the WEB server and avoid leaking provisioning information because of configuration issues.

3.2 Security Rules
Please refer to the Product safety checklist.

Input and output
Check if HTML code is being filtered
Possible problems: If someone enters malicious HTML code, it can lead to stealing cookies, generating malicious login forms, and destroying websites
Check if the variable did escape before doing the database operation
Possible problems: If a string variable to write a query statement contains some special characters, such as quotation marks (', ") or semicolons (;) May cause an operation that is not expected to be performed.
Recommended approach: Use Mysql_escape_string () or a function that implements a similar function.
Check the legitimacy of the input values
Problems that may occur: the value of the exception causes the problem. If the input value is not checked, it will cause illegal or incorrect data to be deposited in udb, stored in other databases or cause unexpected program operation to occur.
Example:
If the program takes the parameter value entered by the user as file name, the file operation, the malicious input system file name can cause system damage.
Verify the use of cookies and the processing of user data
Possible problems: Incorrect cookie usage may result in user data leaks
Access control
For internally used products or for products used by partners, consider increasing access control
Logs
Ensure that the user's confidential information is not recorded in log (for example: User's password)
Ensure full user access records are saved for critical user actions
Https
The transmission of sensitive data to use HTTPS


3.3 Some rules for PHP
Set register_globals = Off (y! PHP has banned register_globals, if you use Y! PHP can not consider this setting)
Set error_reporting = E_all (y! PHP default settings), and to correct all the error and warning
Place the actual action in the referenced file. Put the reference file in a directory that cannot be browsed directly

3.4 Other processing rules

3.4.1 Escape processing of input parameter values
A SQL operation is required for the page to be attached to the parameter, which needs to be escaped, especially ";".
such as: $a = "Let ' s Go";
$sql = "Insert into tmp (COL) VALUES (' $a ')";
There is a false uncertainty about this situation.

3.4.2 Manipulating Large HTML text
Many times you need to store a large piece of HTML text for the page to use, such as a user-defined header footer.
You need to remove the script tag to avoid executing malicious PHP code.
Convert the "<" ">" number to ensure the code is complete.

4 Coding Specifications

4.1 Naming conventions
The development of a unified naming standard for the project is very important, not only can develop a good programmer development habits, but also to increase the readability of the program, portability and reusability, but also to improve the efficiency of project development.

4.1.1 Variable Name
The naming of variables is divided into ordinary variables, static variables, local variables, global variables, session variables, and other naming rules.

4.1.1.1 Common variables
Common variable naming follows these rules:
A All letters are used in lowercase;
b For a variable that uses multiple words, use ' _ ' as the interval for each word.
Example: $base _dir, $red _rose_price, etc.

4.1.1.2 Static variables
Static variable naming follows these rules:
A Static variables start with lowercase s_;
b Static variable all letters are lowercase;
C A variable name consisting of multiple words uses ' _ ' as the interval for each word.
Examples: $s _base_dir, $s _red_rose_prise and so on.

4.1.1.3 Local Variables
Local variable naming follows these rules:
A Use lowercase for all letters;
b The variable starts with ' _ ';
C A local variable name consisting of multiple words uses ' _ ' as the interval between each word.
Examples: $_base_dir, $_red_rose_price and so on.

4.1.1.4 Global Variables
Global variables should be prefixed with ' G ', and it is important to know the scope of a variable.
For example
Global $gLOG _level;
Global $gLOG _path;

4.1.1.5 Global Constants
Global variable naming follows these rules:
A Use uppercase for all letters
b Global variables Use ' _ ' as an interval between multiple words.
Examples: $BASE _dir, $RED _rose_price and so on.

4.1.1.6 Session Variable
Session variable naming follows these rules:
A All letters use uppercase;
b The session variable name begins with ' S_ ';
C Use the ' _ ' interval between multiple words.
Examples: $S _base_dir, $S _red_rose_price and so on.

4.1.2 Class
Class naming in PHP follows these rules:
A Start with a capital letter;
b A variable name consisting of multiple words, with no spacing between words, capitalized on the first letter of each word.
Example: Class MyClass or class dboracle, etc.

4.1.3 method or function
method or function naming follows these rules:
A First letter lowercase;
b No interval is used between multiple words, except for the first word, and the first letter of the other word is capitalized.
Example: function myFunction () or function mydboracle (), etc.

4.1.4 Abbreviated words
When an abbreviation is encountered in a variable name or other naming, refer to the specific naming convention instead of using the original capitalization of the abbreviation.
Example: function mypear (not mypear) Functio Gethtmlsource (not gethtmlsource).

4.1.5 Database table name
database table name naming follows these specifications:
A The table names are in lowercase letters;
b For a normal data table, use the _t end;
C For views, use _v to end;
D For table names consisting of multiple words, use _ interval;
Examples: user_info_t and BOOK_STORE_V, etc.

4.1.6 Database Fields
database field naming follows these specifications:
A all use lowercase;
b Use _ intervals between multiple words.
Examples: user_name, Rose_price and so on.


4.2 Writing Rules
Writing rules refer to the rules for code writing when writing PHP programs, including indentation, structure control, and so on:

4.2.1 Code Indentation
In writing the code, you must pay attention to the code indentation rules, we stipulate that the code indentation rules are as follows:
A Use 4 spaces as indentation instead of tab indent (pre-set for UltraEdit)
Example:
for ($i =0; $i < $count; $i + +)
{
echo "Test";
}

4.2.2 Curly Braces {} writing rules
In the program to write structure control code, such as if, for, while, switch and other structures, curly braces traditionally have two writing habits, as follows:
A {Immediately after the control statement, no line breaks, such as
for ($i =0; $i < $count; $i + +) {
echo "Test";
}
b {A row under the control statement, such as
for ($i =0; $i < $count; $i + +)
{
echo "Test";
}
Among them, a is pear suggested way, but from the actual writing, this does not affect the program's specification and the impact of PHPDOC implementation of the document, so can be based on personal habits to adopt the above two ways, but requires in the same program, only use one of them, in order to avoid the inconvenience of reading.

4.2.3 parentheses () and functions, keywords, etc.
Parentheses, keywords, and functions follow these rules:
A Do not put parentheses and keywords close together, to use a space interval, such as if ($a < $b);
b There are no spaces between parentheses and function names, such as $test = Date ("Ymdhis");
C Do not use parentheses in return return statements unless necessary. such as return $a;

4.2.4 = symbol Writing
The writing of the = symbol in the program follows the following rules:
A On both sides of the = symbol, a space is required, such as $ A = $b, if ($a = = $b), and so on;
b In a declaration block, or to achieve the same function in a block, the required = number as far as possible to it, the left can be used in order to maintain alignment using multiple spaces, and the right requires a blank space;
$testa = $AAA;
$testaa = $BBB;
$TESTAAA = $CCC;

4.2.5 if else swith for while etc. writing
The writing for the control structure follows these rules:
A In the If condition judgment, if a constant is used to determine the condition, place the constant on the left side of the equal or equal sign, for example:
if (6 = = $errorNum), because if you miss an equal sign in the equation, the grammar checker will give you an error, you can quickly find the wrong position, such a way to pay more attention to;
b The default block must be in the switch structure;
C In the use of the For and Wiile, be wary of the use of continue, break, to avoid a similar goto problem;

4.2.6 Constructors for class
If you want to write a constructor inside a class, you must follow these rules:
A You cannot have too many actual operations in the constructor, at most, to initialize some values and variables;
b You cannot return false or an error in a constructor because you are using an operation, because you cannot return an error when declaring and instantiating an object;

4.2.7 statement breaks, each line is controlled within 80 characters
In code writing, follow these guidelines:
A Try to ensure that the program statement line is a sentence, and do not let a line of statements too long to produce a folded line;
b Try not to make a line of code too long, generally control within 80 characters;
C If one line of code is too long, use a similar. = method to write lines;
D For SQL statement operations that execute the database, try not to write the SQL statements inside the function, but first define the SQL statement with the variables, and then invoke the defined variables in the function that performs the operation;
Example:
$sql = "Select Username,password,address,age,postcode from test_t";
$sql. = "WHERE username= ' aaa '";
$res = mysql_query ($sql);

4.2.8 don't make incredible numbers.
A naked number used in the source code is an incredible number, because it includes the author, within three months, no one has its meaning. For example:

if (= = $foo)
{
Start_thermo_nuclear_war ();
}
else if (= = $foo)
{
Refund_lotso_money ();
}
Else
{
Cry_cause_im_lost ();
}
You should use define () to give you a real name for the value you want to represent something, not a naked number, for example:

Define ("President_went_crazy", "22");
Define ("we_goofed", "19");
Define ("They_didnt_pay", "16");

if (President_went_crazy = = $foo)
{
Start_thermo_nuclear_war ();
}
else if (we_goofed = = $foo)
{
Refund_lotso_money ();
}
else if (They_didnt_pay = = $foo)
{
Infinite_loop ();
}
Else
{
Happy_days_i_know_why_im_here ();
}
4.2.9 True/false and 0/1 judgement
Follow these rules:
A You cannot use 0/1 instead of True/false, which is not equal in PHP;
b Do not use non-zero expressions, variables or methods to directly true/false judgment, but must use strict complete true/false judgment;
such as: Do not use if ($a) or if (Checka ()) and if (false! = $a) or if (false! = Check ())

4.2.10 Avoid embedded assignments
Avoid the embedded assignment in the following example in the program:
Do not use such a way:
while ($a! = ($c = GetChar ()))
{
Process the character
}

4.2.11 Error return detection rule
Check all system calls for error messages unless you want to ignore the errors.
Define the system error text for each system error message and log the error log.


4.3 Program notes
Each program must provide the necessary annotations, write the annotation requirements specification, and refer to the annotation requirements provided by pear to prepare for the future use of Phpdoc to generate PHP documents. The principles of program annotations are as follows:
A Note In addition to the header of the comment block, other places do not use//comments, and use/* * * * * * * * *;
b Note Content must be written in front of the annotated object, not written in one line or behind;

4.3.1 Program Header Comment Block
Each program head must have a uniform comment block, the following rules:
A Must contain a description of the program;
b must include the author;
C must contain written date;
D must contain version information;
E Must include the project name;
F Must include the name of the file;
G Important usage instructions, such as the invocation method of the class, precautions, etc.;
Reference examples are as follows:

//
// +---------------------+
// | PHP version 4.0 |
// +---------------------+
// | Copyright (c) 1997-2001 the PHP Group |
// +---------------------+
// | This source file was subject to of the PHP license, |
// | That's bundled with this packafile LICENSE, and are |
// | Available at through-World-web at |
// | Http://www.php.net/license/2_02.txt. |
// | If you do not receive a copy of the and is unable to |
// | Obtain it through the world-wide-web,end a note to |
// | [Email protected] so we can mail you a immediately. |
// +---------------------+
// | Authors:stig Bakken <[email protected]> |
// | Tomas V.v.cox <[email protected]> |
// | |
// +---------------------+
//
$Id: common.php,v 1.8.2.3 2001/11/13 01:26:48 SSB EXP $
Notes for the 4.3.2 class
The comments for the class are in the reference example:

/**
* @ Purpose:
* Classes that access the database, with ODBC as the common provider
* @Package Name:database
* @Author: Forrest Gump [email protected]
* @Modifications:
* NO20020523-100:
* Odbc_fetch_into () parameter position second and third position swap
* John Johnson [email protected]
* @See: (Reference)
*/
Class Database
{
......
}
Comments on 4.3.3 functions and methods
Comments on functions and methods are written in front of the function and method, using a rule similar to the following example:

/**
* @Purpose:
* Execute one query
* @Method Name:query ()
*
* @Param: String $queryStr SQL query string
* @Param: string $username user name
*
* @Author: Michael Lee
*
* @Return: Mixed query return value (Result set object)
*/
function ($QUERYSTR, $username)
{......}
4.3.4 Variable or statement comment
Comments on variables or statements in the program follow these guidelines:
A Write in the front line of a variable or statement, not in the peer or behind;
b Note Using */*/;
C A comment block is included in front of each function. The contents include function summary, input/output parameters, expected return value, error code definition.
D Note the full specification.
E Delete the commented out code, or note that the commented out code remains in the source for a special reason.
F
Example:

/**
* @Purpose:
* Database connection user name
* @Attribute/variable Name:db_user_name
* @Type: string
*/
var db_user_name;

4.4 Other Specifications (recommended)

4.4.1 PHP Code tags
All PHP program code block tags are used

4.4.2 program file name, directory name
Both the program file name and the directory name are named in a meaningful English way, with no pinyin or meaningless letters, and must use lowercase letters, using _ intervals between multiple words.

4.4.3 Common file directory structure for PHP projects
It is recommended to use the canonical file directory structure when developing a separate PHP project for the specification, which helps to rationalize the logical structure of the project, as well as scaling and collaboration, and team development.
A complete standalone PHP project typically has the following file and directory structure:
/Project root directory
/manage Background Management file storage directory
/css CSS File storage directory
/doc Storing project documents
/images all picture file storage paths (in which subdirectories are created according to the directory structure)
/scripts Client JS Script storage directory
/TPL Web site All HTML template file storage directory
/error.php error Handling file (can be defined in Apache error handling)

The above directory structure is the usual directory structure, depending on the specific application of the situation, you can consider not to fully follow, but as far as possible to standardize.

4.4.4 the separation of PHP and HTML code
For projects and applications where performance requirements are not very high, we recommend that you do not write code in a way that is directly mixed with PHP and HTML code, but in a way that is separated by PHP and HTML code, that is, in the form of a template, so that the logical structure of the program is more clear and advantageous, but also helps in the development process Personnel Division , and it also provides more convenience for future project pages to be upgraded to this edition.
For some special cases, such as applications with high performance requirements, you can not use the template mode.

4.4.5 program logic structure in PHP project development
For PHP project Development, try to use the idea of OOP development, especially after PHP5, for the object-oriented development function greatly improved.
In the PHP project, we recommend that the standalone function module be written as a function call, corresponding to a whole block of business logic, and we recommend encapsulation into classes that can improve code readability and code reusability. For example, we usually encapsulate the interface of the database into a database class, which facilitates the porting of the platform.
Duplicate code is made into a common library. (in addition to our experience with plug-in products, the product family has a number of similar products, in order to reduce the size of the installation package as much as possible, it is not suitable for all the functions shared by these products into a common library)

5 Special code for PHP coding in specific environments

5.1 Variable definition
The PHP code in the XXX environment requires all variables to be declared after use, otherwise there will be error messages, for arrays, when using an indeterminate key, such as the first isset () judgment, and then use, such as the following code:
$array = Array ();
$var = Isset ($array [3])? $array [3]: "";

5.2 Use of references
Reference in the program used more, in order to common the same memory, without the need for additional replication, the use of references in the XXX environment, you need to pay attention to the following situation;
When using a reference to the input parameters of a function, it is not possible to add & to the input parameter at the time of the call, but to use the variable directly, and to indicate that the input parameter comes from the reference when the function is defined, such as 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 ";
At this time $a and $b are 2;

The special requirements for references in the XXX environment originate from the Allow_call_time_pass_reference entry setting in the PHP.ini file, and the externally exposed version is on so that the & can be added directly to the reference before the variable is called. But this approach has been protested and may no longer be supported in future versions of the Php/zend. Encouraged to specify which parameters are passed by reference in the function declaration. You are encouraged to try to turn off this option (all running environments with OFF,XXX are off) and verify that your scripts are still working so that they will still work in future versions of the language.

Input and output of 5.3 variables
In the XXX environment, the web through the GET or post method to pass the parameters are required strict filtering and legality verification, not recommended to use direct $_get, $_post or $_request acquisition, and through the Xxx_yiv module of XXX to provide the method of acquisition and filtering processing
  • 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.