Home > Article > Backend Development > Some pitfalls of "==" in PHP
PHP is a weakly typed language and will automatically perform data type conversion, which undoubtedly brings great convenience to our development. But is this really the case? Today we will start with ==.
Example
First, take a look at this code. Guess what the result will be
<?php var_dump(md5('240610708') == md5('QNKCDZO')); var_dump(md5('aabg7XSs') == md5('aabC9RqS')); var_dump(sha1('aaroZmOk') == sha1('aaK1STfY')); var_dump(sha1('aaO8zKZF') == sha1('aa3OFF9m')); var_dump('0010e2' == '1e3'); var_dump('0x1234Ab' == '1193131'); var_dump('0xABCdef' == ' 0xABCdef'); var_dump(0 == 'abcdefg'); var_dump(1 == '1abcdef'); ?>
At first glance, it is obvious that they must all be false, but after running the code, I found that they are all true!
WTF!
Why is this?
I have already said at the beginning that PHP is a weakly typed language. When using == to compare two variables, when one variable is an integer, the other variable will also be converted to an integer. This also explains why 0 == 'abcdefg' and 1 == '1abcdef' are true.
But what about other codes? Can strings still be converted?
The PHP manual provides us with explanations.
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
That is, if you compare two strings involving numbers (eg: "0"), then each string will be converted to a number.
Here, I have to say: PHP is the best language!
Hazard
When our website is directly encrypted by MD5 or Sha1 without adding salt, and it happens that the encryption of a user's password involves numbers, it may be cracked by collision. !
Solution
1. Avoid using == to judge the value of two variables as much as possible during the development process
2.It is best to use password encryption password_hash() or salt md5($pwd.$salt)
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of Some pitfalls of "==" in PHP. For more information, please follow other related articles on the PHP Chinese website!