1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-13 03:45:22 +01:00

[Http] Using streaming hash functions to calculate the Content-MD5 hash of an EntityBody. This is safer because it does not require that the entire contents of a stream be loaded into memory to calculate the MD5 hash.

This commit is contained in:
Michael Dowling 2011-04-08 10:05:41 -05:00
parent 6bff5cbd83
commit 0bc9e1fb80
2 changed files with 20 additions and 2 deletions

View File

@ -199,8 +199,17 @@ class EntityBody extends Stream
*/
public function getContentMd5($rawOutput = false, $base64Encode = false)
{
$data = (string) $this;
$out = ($data !== false) ? md5($data, (bool) $rawOutput) : false;
if (!$this->isSeekable()) {
return false;
}
$this->seek(0);
$ctx = hash_init('md5');
while ($data = $this->read(1024)) {
hash_update($ctx, $data);
}
$out = hash_final($ctx, (bool) $rawOutput);
return ((bool) $base64Encode && (bool) $rawOutput) ? base64_encode($out) : $out;
}

View File

@ -125,5 +125,14 @@ class EntityBodyTest extends \Guzzle\Tests\GuzzleTestCase
{
$body = EntityBody::factory('testing 123...testing 123');
$this->assertEquals(md5('testing 123...testing 123'), $body->getContentMd5());
$server = $this->getServer()->enqueue(
"HTTP/1.1 200 OK" . "\r\n" .
"Content-Length: 3" . "\r\n\r\n" .
"abc"
);
$body = EntityBody::factory(fopen($this->getServer()->getUrl(), 'r'));
$this->assertFalse($body->getContentMd5());
}
}