note 99200 added to function.sha1-file

From: Date: Mon, 02 Aug 2010 20:33:54 +0000
Subject: note 99200 added to function.sha1-file
Groups: php.notes 
Request: Send a blank email to php-notes+get-171344@lists.php.net to get a copy of this message
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(). ---- Server IP: 69.147.83.197 Probable Submitter: 68.226.55.238 ---- Manual Page -- http://www.php.net/manual/en/function.sha1-file.php Edit -- https://master.php.net/note/edit/99200 Del: integrated -- https://master.php.net/note/delete/99200/integrated Del: useless -- https://master.php.net/note/delete/99200/useless Del: bad code -- https://master.php.net/note/delete/99200/bad+code Del: spam -- https://master.php.net/note/delete/99200/spam Del: non-english -- https://master.php.net/note/delete/99200/non-english Del: in docs -- https://master.php.net/note/delete/99200/in+docs Del: other reasons-- https://master.php.net/note/delete/99200 Reject -- https://master.php.net/note/reject/99200 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#171344) next »