note 99200 deleted from function.sha1-file by danbrown

From: Date: Mon, 02 Aug 2010 20:35:58 +0000
Subject: note 99200 deleted from function.sha1-file by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-171345@lists.php.net to get a copy of this message
Note Submitter: john at velvetcache dot org ---- I would not ever use the following, except for small files. <?php $hash = sha1( file_get_contents( $file ) ); ?> That code is saying: 1. Get the _whole_ contents of $file into memory. 2. Pass this to the sha1 function. 3. Return the hash. That can be a big memory grab, depending on your file size. Using sha1_file will progressively read in chunks of the file, and update the hash function with each chunk until it has the whole hash. Here is an example with an 88k JPEG. peak.php <?php echo sha1( file_get_contents( 'test.jpg' ) ) . "\n"; echo memory_get_peak_usage() . "\n"; ?> min.php <?php echo sha1_file( 'test.jpg' ) . "\n"; echo memory_get_peak_usage() . "\n"; ?> And their output: jmhobbs@asuka:/var/www/localhost$ php5 peak.php 9e8d5ee361c6988baf7f75999f2c854a765f3eca 422860 jmhobbs@asuka:/var/www/localhost$ php5 min.php 9e8d5ee361c6988baf7f75999f2c854a765f3eca 330812 That's an 89k difference, almost exactly our file size. Imagine doing this with a 8Mb file. Same hash, better memory profile. Use sha1_file().

« previous php.notes (#171345) next »