Home  >  Article  >  Backend Development  >  Some pitfalls of "==" in PHP

Some pitfalls of "==" in PHP

藏色散人
藏色散人forward
2019-10-11 13:13:393140browse

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(&#39;240610708&#39;) == md5(&#39;QNKCDZO&#39;));
var_dump(md5(&#39;aabg7XSs&#39;) == md5(&#39;aabC9RqS&#39;));
var_dump(sha1(&#39;aaroZmOk&#39;) == sha1(&#39;aaK1STfY&#39;));
var_dump(sha1(&#39;aaO8zKZF&#39;) == sha1(&#39;aa3OFF9m&#39;));
var_dump(&#39;0010e2&#39; == &#39;1e3&#39;);
var_dump(&#39;0x1234Ab&#39; == &#39;1193131&#39;);
var_dump(&#39;0xABCdef&#39; == &#39; 0xABCdef&#39;);
var_dump(0 == &#39;abcdefg&#39;);
var_dump(1 == &#39;1abcdef&#39;);
?>

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete