PHP best way to MD5 multi-dimensional array?

后端 未结 13 2014
别那么骄傲
别那么骄傲 2020-12-07 11:48

What is the best way to generate an MD5 (or any other hash) of a multi-dimensional array?

I could easily write a loop which would traverse through each level of the

13条回答
  •  眼角桃花
    2020-12-07 12:24

    Important note about serialize()

    I don't recommend to use it as part of hashing function because it can return different result for the following examples. Check the example below:

    Simple example:

    $a = new \stdClass;
    $a->test = 'sample';
    
    $b = new \stdClass;
    $b->one = $a;
    $b->two = clone $a;
    

    Produces

    "O:8:"stdClass":2:{s:3:"one";O:8:"stdClass":1:{s:4:"test";s:6:"sample";}s:3:"two";O:8:"stdClass":1:{s:4:"test";s:6:"sample";}}"
    

    But the following code:

    test = 'sample';
    
    $b = new \stdClass;
    $b->one = $a;
    $b->two = $a;
    

    Output:

    "O:8:"stdClass":2:{s:3:"one";O:8:"stdClass":1:{s:4:"test";s:6:"sample";}s:3:"two";r:2;}"
    

    So instead of second object php just create link "r:2;" to the first instance. It's definitely good and correct way to serialize data, but it can lead to the issues with your hashing function.

提交回复
热议问题