- PHP best way to MD5 multi-dimensional array
- Best Solution
- Php md5 от массива
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 7 notes
- Saved searches
- Use saved searches to filter your results more quickly
- License
- lindowx/php-array-hash
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
PHP best way to MD5 multi-dimensional array
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 array, concatenating each value into a string, and simply performing the MD5 on the string.
However, this seems cumbersome at best and I wondered if there was a funky function which would take a multi-dimensional array, and hash it.
Best Solution
(Copy-n-paste-able function at the bottom)
As mentioned prior, the following will work.
However, it’s worth noting that (ironically) json_encode performs noticeably faster:
In fact, the speed increase is two-fold here as (1) json_encode alone performs faster than serialize, and (2) json_encode produces a smaller string and therefore less for md5 to handle.
Edit: Here is evidence to support this claim:
i:1;a:3:i:1;a:0:<>i:2;a:3:i:1;a:0:<>i:2;a:0:<>>>i:2;s:5:"hello";i:3;a:2:i:1;a:0:<>>i:4;a:1:>>>>>i:5;a:5:i:1;a:4:i:1;a:0:<>i:2;a:3:i:1;a:0:<>i:2;a:0:<>>i:3;a:6:i:1;a:3:i:1;a:0:<>i:2;a:3:i:1;a:0:<>i:2;a:0:<>>>i:2;s:5:"hello";i:3;a:2:i:1;a:0:<>>i:4;a:1:>>>>>i:5;a:5:i:1;a:3:i:1;a:0:<>i:2;a:3:i:1;a:0:<>i:2;a:0:<>>>i:2;s:5:"hello";i:3;a:2:i:1;a:0:<>>i:4;a:1:>>>>>>>>i:2;s:5:"hello";i:3;a:2:i:1;a:0:<>>i:4;a:1:>>>>>>>'); //The serialize test $b4_s = microtime(1); for ($i=0;$i <10000;$i++) < $serial = md5(serialize($array)); >echo 'serialize() w/ md5() took: '.($sTime = microtime(1)-$b4_s).' sec
'; //The json test $b4_j = microtime(1); for ($i=0;$i <10000;$i++) < $serial = md5(json_encode($array)); >echo 'json_encode() w/ md5() took: '.($jTime = microtime(1)-$b4_j).' sec
'; echo 'json_encode is '.( round(($sTime/$jTime)*100,1) ).'% faster with a difference of '.($sTime-$jTime).' seconds';
JSON_ENCODE is consistently over 250% (2.5x) faster (often over 300%) — this is not a trivial difference. You may see the results of the test with this live script here:
Now, one thing to note is array(1,2,3) will produce a different MD5 as array(3,2,1). If this is NOT what you want. Try the following code:
//Optionally make a copy of the array (if you want to preserve the original order) $original = $array; array_multisort($array); $hash = md5(json_encode($array));
Edit: There’s been some question as to whether reversing the order would produce the same results. So, I’ve done that (correctly) here:
As you can see, the results are exactly the same. Here’s the (corrected) test originally created by someone related to Drupal:
And for good measure, here’s a function/method you can copy and paste (tested in 5.3.3-1ubuntu9.5):
function array_md5(Array $array) < //since we're inside a function (which uses a copied array, not //a referenced array), you shouldn't need to copy the array array_multisort($array); return md5(json_encode($array)); >
Php md5 от массива
md5 — Возвращает MD5-хеш строки
Не рекомендуется использовать эту функцию для обеспечения безопасности хранения паролей ввиду высокой скорости работы данного алгоритма. Более подробно читайте в разделе Ответы на часто задаваемые вопросы по хешированию паролей.
Описание
Вычисляет MD5-хеш строки string , используя » алгоритм MD5 RSA Data Security, Inc. и возвращает этот хеш.
Список параметров
Если необязательный аргумент binary имеет значение true , то возвращается бинарная строка из 16 символов.
Возвращаемые значения
Возвращает хеш в виде 32-символьного шестнадцатеричного числа.
Примеры
Пример #1 Пример использования md5()
if ( md5 ( $str ) === ‘1afa148eb41f2e7103f21410bf48346c’ ) echo «Вам зелёное или красное яблоко?» ;
>
?>
Смотрите также
- md5_file() — Возвращает MD5-хеш файла
- sha1_file() — Возвращает SHA1-хеш файла
- crc32() — Вычисляет полином CRC32 для строки
- sha1() — Возвращает SHA1-хеш строки
- hash() — Генерирует хеш-код (подпись сообщения)
- crypt() — Необратимое хеширование строки
- password_hash() — Создаёт хеш пароля
User Contributed Notes 7 notes
This comparison is true because both md5() hashes start ‘0e’ so PHP type juggling understands these strings to be scientific notation. By definition, zero raised to any power is zero.
Regarding Ray Paseur’s comment, the strings hash to:
The odds of getting a hash exactly matching the format /^0+e9+$/ are not high but are also not negligible.
It should be added as a general warning for all hash functions to always use the triple equals === for comparison.
Actually, the warning should be in the operators section when comparing string values! There are lots of warnings about string comparisons, but nothing specific about the format /^0+e4+$/.
If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.
This allows you to hash chunks/parts/incremental or whatever you like to call it.
I’ve found multiple sites suggesting the code:
Until recently, I hadn’t noticed any issues with this locally. but then I tried to hash a 700MB file, with a 2048MB memory limit and kept getting out of memory errors.
There appears to be a limit to how long a string the md5() function can handle, and the alternative function is likely more memory efficient anyway. I would highly recommend to all who need file hashing (for detecting duplicates, not security digests) use the md5_file() function and NOT the regular string md5() function!
Note, to those interested, as this was for a local application not a server, I was more concerned with results than memory efficiency. In a live environment, you would never want to read an entire file into memory at once when avoidable. (at the time of coding, I did not know of the alternative function)
From the documentation on Digest::MD5:
md5($data. )
This function will concatenate all arguments, calculate the MD5 digest of this «message», and return it in binary form.
md5_hex($data. )
Same as md5(), but will return the digest in hexadecimal form.
PHP’s function returns the digest in hexadecimal form, so my guess is that you’re using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP’s md5() function.
(original comment snipped in various places)
>Hexidecimal hashes generated with Perl’s Digest::MD5 module WILL
>NOT equal hashes generated with php’s md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5(‘pa$$’);
>echo «php original hash from text: $phphash»;
>echo «md5 hash from perl: » . $myrow[‘password’];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd
function raw2hex ( $rawBinaryChars )
return = array_pop ( unpack ( ‘H*’ , $rawBinaryChars ));
>
?>
The complement of hey2raw.
You can use to convert from raw md5-format to human-readable format.
?php
This can be usefull to check «Content-Md5» HTTP-Header.
$rawMd5 = base64_decode ( $_SERVER [ ‘HTTP_CONTENT_MD5’ ]);
$post_data = file_get_contents ( «php://input» );
if( raw2hex ( $rawMd5 ) == md5 ( $post_data )) // Post-Data is okay
else // Post-Data is currupted
?>
Note: Before you get some idea like using md5 with password as way to prevent others tampering with message, read pages «Length extension attack» and «Hash-based message authentication code» on wikipedia. In short, naive constructions can be dangerously insecure. Use hash_hmac if available or reimplement HMAC properly without shortcuts.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Hashing a multi-dimension PHP array into a unique string value
License
lindowx/php-array-hash
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A PHP array hashing library that can hashing multi-dimension array into a unique string value.
composer require lindowx/php-array-hash
/** * Array hashing * * @param array $arr The array data you want to hash * @param callable $func Hash algo function * @param int $options Hashing options */ Lindowx\PHPArrayHash\ArrayHash::hash(array $arr, callable $func, int $options = 0): string;
- ArrayHash::OPT_NIA_IGNORE_ORDER Ignore the value order when the source array contains num-index lists
use Lindowx\PHPArrayHash\ArrayHash; $arr1 = [ 'a' => 3, 'b' => 'hello, world', 'c' => [ [1, 2, 3], [4, 5, 6], ], ]; $arr2 = [ 'a' => 3, 'b' => 'hello, world', 'c' => [ [4, 6, 5], [3, 1, 2], ], ]; // SHA-1 hashing // 4dea90f136ff0bdeb8da5a7da0f03b1858d62b16 $arrSha1Hash = ArrayHash::hash($arr1, 'sha1'); // MD5 hashing // 32a02c4310e4c71c27fd5a42b25d0e73 $arrMd5Hash = ArrayHash::hash($arr1, 'md5'); // Custom hashing //09ce8e0554ed842d50162e28710331415735e7f618b1caa396f28ab0f3cd99d9 $arrCustomHash = ArrayHash::hash($arr1, function ($stub) < $key = 'this is a key'; return hash_hmac('sha256', $stub, $key); >); // 80895b6e8ab6d0d4d1201f84b3ba8b5f70bb50ea $arr1Sha1NumIdxListIgnoreOrder = ArrayHash::hash($arr1, 'sha1', ArrayHash::OPT_NIA_IGNORE_ORDER); // 80895b6e8ab6d0d4d1201f84b3ba8b5f70bb50ea $arr2Sha1NumIdxListIgnoreOrder = ArrayHash::hash($arr2, 'sha1', ArrayHash::OPT_NIA_IGNORE_ORDER);
The MIT License (MIT). Please see License File for more information.