. Net programmers learn PHP: common programming errors

Source: Internet
Author: User
Tags php compiler php exception handling
ArticleDirectory
    • 1. small mistakes can make a big disaster
    • 2. I forgot to add a semicolon after break or continue.
    • 3. Single or double quotation marks?
    • 4. Compare floating point numbers
    • 5. Can we call method_exists () if the returned result is true?
    • 6. Use uninitialized Arrays
    • 10. Use = to compare the data type.
    • 11. The empty () method and the magic method _ Get are used together.
    • 12. No protection for sensitive data in the session

In this article, I will continue my PHP journey and collect and summarize some common PHP errors found on the internet, hoping to help you.

1. small mistakes can make a big disaster

You met a small semicolon.ProgramIs there a big problem? In PHP, if you add a semicolon after the while loop condition, PHP will be in an endless loop, and such error settings will not be captured by the PHP exception handling system. Let's take a look.CodeRight:

  $ I     =    0  ;
While ( $ I < 20 );{
// Some code here
$ I ++ ;
}
Echo $ I ;

This Code does not cause errors reported by the system, but it will lead to an endless loop of the system and eventually return the execution timeout error because of the inability to respond in a timely manner.

However, C # will also be captured by the compiler during compilation, and the compiler will know that this is a null Loop Error. Of course, if the user must be stupid enough to write another endless loop compiler, there will be no way, such:

  IntI= 0;
While(I< 20);

In this case, the compiler will not report an error.

2. I forgot to add a semicolon after break or continue.

It is also a small symbol that causes a huge difference. Let's look at the following code first:

  For ($ I  =     0  ; $ I  <     10  ; $ I  ++  ){
For ($ J = 0 ; $ J < 10 ; $ J ++ ){
If ($ I = 0 )
Break
Print $ J;
}
}

This code will only output 0 results and exit the loop. However, our intention is to output other numbers except 0. Of course, it is easy to avoid this error if we use a standard method (such as adding brackets after the if condition is determined.

3. Single or double quotation marks?

Strictly speaking, this article cannot be regarded as an error. First, let's look at the following two lines of code:

  Echo'It \'s OK ';
Echo"It's not ";

 

PHP is not like C #. Single quotes and double quotation marks can be used to represent strings. Therefore, many new PHP users often cannot tell when to use the symbols to enclose strings, or simply use the symbols when to use them. However, single quotes and double quotes are skillful in PHP. If a string starts with double quotation marks, only the double quotation marks are parsed by the analyzer. In this way, you can include any other characters in the double quotation marks, or even single quotation marks and PHP variables. E.g.

  $ Var1  =  'Sean zhu ';
Echo 'Hello , $ Var1 . I'm Mike ! '; // Output: Hello, $ var1. I'm Mike!
Echo "Hello , $ Var1 . I'm Mike ! "; // Output: Hello, Sean Zhu. I'm Mike!

However, the larger the capability, the larger the consumption, and the complicated function of double quotation marks also means that the compiler takes more time to process it. Therefore, if we only want to output a simple string, it is best to use single quotes.

4. Compare floating point numbers

As A. Net programmer, do you know the result of the following code?

  <?  PHP
$ = 0.1 + 0.2 ;
$ B = 0.3 ;
If ( $ = $ B ){
Echo ' A equals B ' ;
}
Else {
Echo ' A dosen \ ' T equal B ' ;
}
?>

In. net, we can know without hesitation that it outputs the answer of a = B, but here is the PHP world, so never believe that the floating point result is accurate to the last one, do not compare two floating point numbers for equality.

5. Can we call method_exists () if the returned result is true?

PHP is not like C #. Since C # Is a static language, we can call any method with confidence (as long as the compiler says no problem ), however, in PHP, everything remains unknown as long as you fail to execute the final method. Therefore, we sometimes need to perform additional checks before calling the method. method_exist () is one of them. However, if the method is protected or private, the method returns true.

6. Use uninitialized Arrays

Let's take a look at the following code?

   code highlighting produced by actipro codehighlighter (freeware) 
http://www.CodeHighlighter.com/
--> php
foreach ( $ items as $ item ) {
$ itemids [] = $ item -> GETID ();
}< br> ?>

. Net programmers will never make the above mistakes, because the compiler will help us check. However, as a PHP programmer, we always have to remember to initialize the array: $ itemids = array (); you may say that the above Code is not initialized and there will be no problems. Yes. Normally, when the element in the $ items array is greater than 1, this code is OK. However, if the $ items object is empty or the number of elements in it is 0, this code will be faulty.

7. Include ("pages/". $ _ Get ["PG1"]);

. Net programmers may also encounter various injection attacks, but at least they will not. In fact, we should check not only the $ _ Get () parameter, but also other values such as $ _ post and $ _ request are highly risky. If you always trust users, you may not know how to load others' code without knowing it.

8. Add quotation marks to the array index
  Echo $ Array[My_key];//It works normally, but should not be used
Echo $ Array['My_key'];//The correct method

The PHP compiler will think that a string without quotation marks is a defined constant, and then it will find this constant in the symbol table, only when it cannot be found, it converts the key value to a real string, which is why the above Code can also work.

9. strpos/ The stripos function is improperly used.

This function also has a similar in. Net: String. indexof (), but in. net we generally do not make this elementary error. Let's take a look at the following code.

   code highlighting produced by actipro codehighlighter (freeware) 
http://www.CodeHighlighter.com/
--> If ( strpos ('spring brother is cool , isn' t it ? ' , 'spring brother ') {
echo " Spring brother is cool ";
} else {< br> echo " Spring brother is not cool ";
}

Guess what the output result is? Yes, it will output "Spring brother is not cool", because, just like in. net, as the index starts from 0, strpos returns 0 to false. In. net, if the programmer does not perform a forced conversion, this error is easily displayed.

The solution to this primary error is also very simple. There are two common methods:

  If  (  Strpos  ('Spring brother is cool  ,  Isn' t it  ?  '  ,  'Spring brother)  ! =    False  ){
// Or
If ( Strpos ('Spring brother is cool , Isn' t it ? ' , 'Spring brother ') > = 0 ){
10. Use = to compare the data type.

This error is actually the same as in JS. Because PHP and JS are both weak languages, we may encounter unexpected things when comparing two objects. See the following code:

  $     =     1  ;
$ B = ' 1 ′;
$ C = 1 ;
$ = $ B // True
$ === $ B // False
$ === $ C // True

We can see that even if $ A and $ B are not the same object, the result of = comparing returns is true, therefore, we recommend that you use = and! = Comparison character.

11. The empty () method and the magic method _ Get are used together.

The magic method is very useful, but when it is used with the empty method, we need to be very careful, first go to the Code:

Code

  Class  Example {
Public Function _ Get ( $ Name ){
Return ' This shoshould not show up as empty ' ;
}
}
Function T7 (){
$ E = New Example ();
If ( Empty ( $ E -> Something ))
Echo ' The something condition is true. ' ;

$ VaR = $ E -> Something;
If ( Empty ( $ VaR ))
Echo ' $ VaR is true. ' ;
}
T7 ();

We will find that the first condition is true, but the same value is false in the second condition.

12. No protection for sensitive data in the session

A common PHP security error is that it does not encrypt any type of sensitive data stored in the session. To some extent, this is equivalent to exposing the user's password and other information to the network. Some hackers can steal the user's password information through sesion forgery and other technologies.

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.