hash_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_fileファイルの内容から、ハッシュ値を生成する

説明

hash_file(
    string $algo,
    string $filename,
    bool $binary = false,
    array $options = []
): string|false

パラメータ

algo

選択したアルゴリズムの名前 (例: "sha256")。 サポートされているアルゴリズムの一覧は hash_algos() を参照ください。

filename

ハッシュ対象となるファイルの位置を示す URL。 fopen() ラッパーをサポートしています。

binary

true を設定すると、生のバイナリデータを出力します。 false の場合は小文字の 16 進数値となります。

options

様々なハッシュアルゴリズム向けの、オプションの配列。 現状は、MurmurHash バリアントが "seed" だけをサポートしています。

戻り値

binary が true に設定されていない場合は、 メッセージダイジェストの計算結果を小文字の 16 進数値形式の文字列で 返します。もし true に設定されていた場合は、メッセージダイジェストが そのままのバイナリ形式で返されます。

変更履歴

バージョン 説明
8.1.0 options パラメータが追加されました。

例1 hash_file() の使用例

<?php
/* ハッシュ値を計算するファイルを作成します */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo
hash_file('sha256', 'example.txt');
?>

上の例の出力は以下となります。

68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

参考

  • hash_init() - 段階的なハッシュコンテキストを初期化する
  • hash_hmac_file() - HMAC 方式を使用して、指定されたファイルの内容からハッシュ値を生成する

add a note

User Contributed Notes 8 notes

up
10
apm at domain itsmee.co.uk
14 years ago
I have verified that the output of the "crc32" is the ITU I.363.5 algorithm (a.k.a. AAL5 CRC - popularised by BZIP2 but also used in ATM transmissions - the algorithm is the same as that in POSIX 1003.2-1992 in Cksum but that stuffs the size into the CRC at the end for extra measure).  However, the output is expressed in reverse order to many CRC programs.  Using the "standard" crctest.txt (numbers 1 to 9 in sequence - google it, it's not hard to find), php will output 181989fc - many other (Intel little endian) programs would output this as fc891918, hence the confusion (that I have had, at least).The crc32b is the 32-bit Frame Check Sequence of ITU V.42 (used in Ethernet and popularised by PKZip).  The output from this CRC is popularised in Intel little endian format and would produce cbf43926 on the same file.
up
12
synnus at gmail dot com
10 years ago
bench 476 Mo, win is 'haval160,4' : 0.037002ALGO: md2, time: 74.702272891998ALGO: md4, time: 9.2155270576477ALGO: md5, time: 9.0815191268921ALGO: sha1, time: 9.0945210456848ALGO: sha224, time: 9.1465229988098ALGO: sha256, time: 9.143522977829ALGO: sha384, time: 14.065804004669ALGO: sha512, time: 13.990800857544ALGO: ripemd128, time: 9.3185329437256ALGO: ripemd160, time: 9.3165328502655ALGO: ripemd256, time: 9.2495288848877ALGO: ripemd320, time: 9.2395279407501ALGO: whirlpool, time: 27.779588937759ALGO: tiger128,3, time: 9.3075330257416ALGO: tiger160,3, time: 9.1875250339508ALGO: tiger192,3, time: 9.3875370025635ALGO: tiger128,4, time: 9.1755249500275ALGO: tiger160,4, time: 9.355535030365ALGO: tiger192,4, time: 9.2025260925293ALGO: snefru, time: 42.781446218491ALGO: snefru256, time: 42.613437175751ALGO: gost, time: 18.606064081192ALGO: gost-crypto, time: 18.664067983627ALGO: adler32, time: 9.1535229682922ALGO: crc32, time: 10.126579999924ALGO: crc32b, time: 10.01757311821ALGO: fnv132, time: 9.7505569458008ALGO: fnv1a32, time: 9.7935597896576ALGO: fnv164, time: 9.8945660591125ALGO: fnv1a64, time: 9.3025319576263ALGO: joaat, time: 9.7175559997559ALGO: haval128,3, time: 9.6855540275574ALGO: haval160,3, time: 10.10857796669ALGO: haval192,3, time: 9.6765530109406ALGO: haval224,3, time: 20.636180877686ALGO: haval256,3, time: 10.641607999802ALGO: haval128,4, time: 7.5594329833984ALGO: haval160,4, time: 7.2884171009064ALGO: haval192,4, time: 7.2934169769287ALGO: haval224,4, time: 7.2964169979095ALGO: haval256,4, time: 7.3034179210663ALGO: haval128,5, time: 8.3244760036469ALGO: haval160,5, time: 8.3174757957458ALGO: haval192,5, time: 8.3204758167267ALGO: haval224,5, time: 8.3234758377075ALGO: haval256,5, time: 8.3254759311676bench 13,0 Mo, win is 'adler32'  : 0.037002ALGO: md2, time: 2.0341160297394ALGO: md4, time: 0.062004089355469ALGO: md5, time: 0.071003913879395ALGO: sha1, time: 0.086004972457886ALGO: sha224, time: 0.18301010131836ALGO: sha256, time: 0.18301105499268ALGO: sha384, time: 0.36102104187012ALGO: sha512, time: 0.3610200881958ALGO: ripemd128, time: 0.15900897979736ALGO: ripemd160, time: 0.20701193809509ALGO: ripemd256, time: 0.16500997543335ALGO: ripemd320, time: 0.22501301765442ALGO: whirlpool, time: 0.74204206466675ALGO: tiger128,3, time: 0.12200689315796ALGO: tiger160,3, time: 0.12100696563721ALGO: tiger192,3, time: 0.12200713157654ALGO: tiger128,4, time: 0.15700888633728ALGO: tiger160,4, time: 0.15700888633728ALGO: tiger192,4, time: 0.15600895881653ALGO: snefru, time: 1.1520659923553ALGO: snefru256, time: 1.151065826416ALGO: gost, time: 0.48902797698975ALGO: gost-crypto, time: 0.49202799797058ALGO: adler32, time: 0.037002086639404ALGO: crc32, time: 0.10300588607788ALGO: crc32b, time: 0.093006134033203ALGO: fnv132, time: 0.043002128601074ALGO: fnv1a32, time: 0.045002937316895ALGO: fnv164, time: 0.12800693511963ALGO: fnv1a64, time: 0.12800693511963ALGO: joaat, time: 0.070003986358643ALGO: haval128,3, time: 0.12900686264038ALGO: haval160,3, time: 0.12800693511963ALGO: haval192,3, time: 0.12900805473328ALGO: haval224,3, time: 0.12800693511963ALGO: haval256,3, time: 0.12800693511963ALGO: haval128,4, time: 0.19901204109192ALGO: haval160,4, time: 0.1990110874176ALGO: haval192,4, time: 0.20001196861267ALGO: haval224,4, time: 0.20001101493835ALGO: haval256,4, time: 0.20001220703125ALGO: haval128,5, time: 0.22601294517517ALGO: haval160,5, time: 0.2270131111145ALGO: haval192,5, time: 0.2270131111145ALGO: haval224,5, time: 0.2270131111145ALGO: haval256,5, time: 0.22701287269592
up
8
chernyshevsky at hotmail dot com
14 years ago
If you want to use hash_file() to get the CRC32 value of a file, use the following to unpack the hex string returned by the function to an integer (similar to crc32()):$hash = hash_file('crc32b', $filepath);$array = unpack('N', pack('H*', $hash));$crc32 = $array[1];
up
3
Lawrence Cherone
7 years ago
It's sometimes necessary to hash the same file with different algos, <?phpfunction hash_file_multi($algos = [], $filename) {    if (!is_array($algos)) {        throw new \InvalidArgumentException('First argument must be an array');    }    if (!is_string($filename)) {        throw new \InvalidArgumentException('Second argument must be a string');    }    if (!file_exists($filename)) {        throw new \InvalidArgumentException('Second argument, file not found');    }    $result = [];    $fp = fopen($filename, "r");    if ($fp) {        // ini hash contexts        foreach ($algos as $algo) {            $ctx[$algo] = hash_init($algo);        }        // calculate hash        while (!feof($fp)) {            $buffer = fgets($fp, 65536);            foreach ($ctx as $key => $context) {                hash_update($ctx[$key], $buffer);            }        }        // finalise hash and store in return        foreach ($algos as $algo) {            $result[$algo] = hash_final($ctx[$algo]);        }        fclose($fp);    } else {        throw new \InvalidArgumentException('Could not open file for reading');    }       return $result;}?>Which would be used like:<?php$result = hash_file_multi(['md5', 'sha1', 'sha256'], 'path/to/file.ext');var_dump($result['md5'] === hash_file('md5', 'path/to/file.ext')); //truevar_dump($result['sha1'] === hash_file('sha1', 'path/to/file.ext')); //truevar_dump($result['sha256'] === hash_file('sha256', 'path/to/file.ext')); //true
up
3
Keisial at gmail dot com
16 years ago
The 'octets reversed' you are seeing is the bug 45028 which has been fixed. http://bugs.php.net/bug.php?id=45028The difference between crc32 and crc32b is explained on mhash man page. crc32 is the one used on ethernet, while crc32b is the one used on zip, png... They differ on the table used.
up
3
holdoffhunger at gmail dot com
13 years ago
The Hash_File() function returns the same value as if the function Hash() had been performed on the same exact piece of data.  At first, I was uncertain if Hash_File() used the filename, or even the permission settings, when defining the data to be hashed for the given algorithm.  If it did work that way, then that means the same exact files would have different HASH values when you moved or renamed them on your system.  Anyway, fortunately, it does not work that way.  Hash() and Hash_File() produce identical results for the same pieces of data.  This is also true for the relationship between the Hash_HMAC() and Hash_HMAC_File() functions: the same pieces of data, the same keys, produce identical results.  It was a wise, design principle.Some sample code to demonstrate this principle :<?php            // Author: holdoffhunger@gmail.com        // Preset Data        // ------------------------------------------------            $test_data = "php-hashing";    $test_file = "test.txt";    $test_file_read = file_get_contents($test_file);            // Hash Data        // ------------------------------------------------        $test_data_hash = hash("md2", $test_data, FALSE);    $test_file_hash = hash_file("md2", $test_file, FALSE);            // Print Hash Results        // ------------------------------------------------        print("Data Hash ($test_data): $test_data_hash<br><br>");    print("File Hash ($test_file_read): $test_file_hash");    ?>    Expected Results    ..................................    Data Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3File Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3
up
-3
Anonymous
14 years ago
Please take note that hash-file will throw error on files >=2GB.
up
-2
lnker dot ua at gmail dot com
7 years ago
Link id : 6r1j-d2gsCode description : hash_file() performance check; Table head columns are sortable by clicking;Open the code with PhpFiddle - http://phpfiddle.org/main/code/6r1j-d2gsOpen the code with PhpFiddle Lite - http://phpfiddle.org/lite/code/6r1j-d2gsSo do not care a lot about performance! Just use what you need!
To Top