string sha1_file ( string filename [, bool raw_output])
string md5_file ( string filename [, bool raw_output])
Back in earlier days of the internet, most files took a long time to download, and users frequently found they ended up with corrupted downloads. Even today, with ADSL and cable modems being common place, many downloads take a little time to complete, and errors still do occur.
To combat the chance of people downloading bad files and not realising, and also to make sure people know they have an official copy of a file/program, it became popular practice to create a checksum hash value using algorithms such as SHA1. By attaching a hash value this way allows downloaders to check their copy of a file to make sure it matches the web site's hash value - if it does not, the file is not the same.
Because this process of checksumming files is so common, there is a function specifically for it, sha1_file(), which works in roughly the same way as the sha1() function we looked at previously - you feed it the filename of a file you want to checksum, and it returns the SHA1 hash value.
Given the variable $filename is set to a valid filename, these two lines of code are functionally identical:
<?php $sha1 = sha1_file($filename); $sha1 = sha1(file_get_contents($filename)); ?>
The only real difference between the two is that the first line is about 20% faster than the second.
For MD5 hashing, you can use the function md5_file(). It works in exactly the same way as sha1_file(), except that it returns the MD5 hash as opposed to the SHA1 hash.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Parsing a configuration file >>
Previous chapter: Remote files
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.