The 7th Annual China PHP Conference


(PHP 4, PHP 5, PHP 7)

md5Возвращает MD5-хеш строки


Не рекомендуется использовать эту функцию для обеспечения безопасности хранения паролей ввиду высокой скорости работы данного алгоритма. Более подробно читайте в разделе Ответы на часто задаваемые вопросы по хешированию паролей.


md5 ( string $str [, bool $raw_output = FALSE ] ) : string

Вычисляет MD5-хеш строки str, используя » алгоритм MD5 RSA Data Security, Inc. и возвращает этот хеш.

Список параметров




Если необязательный аргумент raw_output имеет значение TRUE, то возвращается бинарная строка из 16 символов.

Возвращаемые значения

Возвращает хеш в виде 32-символьного шестнадцатеричного числа.


Пример #1 Пример использования md5()


if (
md5($str) === '1afa148eb41f2e7103f21410bf48346c') {
"Вам зеленое или красное яблоко?";

Смотрите также

  • md5_file() - Возвращает MD5-хеш файла
  • sha1_file() - Возвращает SHA1-хеш файла
  • crc32() - Вычисляет полином CRC32 для строки
  • sha1() - Возвращает SHA1-хеш строки
  • hash() - Генерирует хеш-код (дайджест сообщения)
  • crypt() - Необратимое хеширование строки
  • password_hash() - Создает хеш пароля

add a note add a note

User Contributed Notes 8 notes

Ray.Paseur sometimes uses Gmail
6 months ago
md5('240610708') == md5('QNKCDZO')

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.
radon8472 at radon-software dot net
3 years ago
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.

This can be usefull to check "Content-Md5" HTTP-Header.

= base64_decode($_SERVER['HTTP_CONTENT_MD5']);
$post_data = file_get_contents("php://input");

raw2hex($rawMd5) == md5($post_data)) // Post-Data is okay
else                                    // Post-Data is currupted
Ken Guest
1 month ago
Use the strict comparision/identity operator:

php > var_dump(md5('240610708') == md5('QNKCDZO'));
php shell code:1:
php > var_dump(md5('240610708') === md5('QNKCDZO'));
php shell code:1:
php >

because, as mentioned previously, using the equality operator may result in false positives.
1 year ago
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.
Shane Allen
16 years ago
From the documentation on Digest::MD5:
This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form.

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'];
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd
terry _at_ scribendi_com
14 years ago
Do not use the hex strings returned by md5() as a key for MCrypt 256-bit encryption.  Hex characters only represent four bits each, so when you take 32 hex characters, you are only really using a 128-bit key, not a 256-bit one. 

Using an alphanumeric key generator [A-Za-z0-9] will also only provide a 192-bit key in 32 characters.

Two different MD5s concatenated in raw binary form, or mcrypt_create_iv(32,MCRYPT_DEV_RANDOM) will give you a true 256-bit key string.
dionyziz at deviantart dot com
11 years ago
Sometimes it's useful to get the actual, binary, md5 digest.
You can use this function for it:


function md5bin( $target ) {
$md5 = md5( $target );
$ret = '';

    for (
$i = 0; $i < 32; $i += 2 ) {
$ret .= chr( hexdec( $md5{ $i + 1 } ) + hexdec( $md5{ $i } ) * 16 );


9 years ago
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.
To Top