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

hash_fileGenera un valor cifrado usando el contenido de un fichero dado


string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )



Nombre del algoritmo de cifrado seleccionado (es decir "md5", "sha256", "haval160,4", etc..)


URL que describe la localización del fichero cuyo contenido vamos a cifrar; Soporta fopen wrappers.


Cuando se establece en TRUE la salida serán datos binarios sin formato, FALSE la salida serán dígitos hexadecimales en minúsculas.

Valores devueltos

Devuelve un string que contiene el mensaje cifrado como dígitos hexadecimales en minúsculas, a menos que raw_output sea establecido en true, en cuyo caso la salida devuelta será el mensaje cifrado como datos binarios sin formato.


Ejemplo #1 Usando hash_file()

/* Creamos un fichero para calcular su resultante valor cifrado */
file_put_contents('example.txt''The quick brown fox jumped over the lazy dog.');


El resultado del ejemplo sería:


Ver también

  • hash() - Genera un valor cifrado con base a un string
  • hash_hmac_file() - Genera un valor cifrado mediante una clave especificada usando el método HMAC y el contenido de un fichero dado
  • hash_update_file() - Inyecta datos en un contexto de cifrado activo desde un fichero
  • md5_file() - Calcula el resumen criptográfico md5 de un archivo dado
  • sha1_file() - Calcula el hash sha1 de un archivo

add a note add a note

User Contributed Notes 6 notes

chernyshevsky at hotmail dot com
4 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];
4 years ago
Please take note that hash-file will throw error on files >=2GB.
Keisial at gmail dot com
6 years ago
The 'octets reversed' you are seeing is the bug 45028 which has been fixed. http://bugs.php.net/bug.php?id=45028

The 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.
holdoffhunger at gmail dot com
2 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 :


// 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>");
"File Hash ($test_file_read): $test_file_hash");

    Expected Results
Data Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3

File Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3
apm at domain itsmee.co.uk
3 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.
allaryin at gmail dot com
6 years ago
For those who are wondering, there appears to be no fundamental difference between hash_file('md5')/hash_file('sha1') and md5_file()/sha1_file(). They produce identical output and have comparable performance.

There is, however, a difference between hash_file('crc32') and something silly like crc32(file_get_contents()).

crc32(file_get_contents())'s results are most similar to those of hash_file('crc32b'), just with the octets reversed:

= "something.png";

$hash = hash_file( 'crc32', $fname );
"crc32  = $hash\n";

$hash = hash_file( 'crc32b', $fname );
"crc32b = $hash\n";

$hash = sprintf("%x",crc32(file_get_contents($fname)));
"manual = $hash\n";

crc32  = f41d7f4e
crc32b = 7dafbba4
manual = a4bbaf7d
To Top