php-http / message

HTTP Message related tools
http://php-http.org
MIT License
1.29k stars 41 forks source link

Stream verification #25

Open sagikazarmark opened 8 years ago

sagikazarmark commented 8 years ago

Utilize stream filters to verify the content of stream.

For example an md5 verification:

class MD5 extends \php_user_filter
{
    private $context;

    public function onCreate()
    {
        $this->context = hash_init('md5');

        return true;
    }

    public function onClose()
    {
        $hash = hash_final($this->context);

        if (false === hash_equals($this->params, $hash)) {
            throw new VerificationException('The stream integrity cannot be verified');
        }

        return true;
    }

    public function filter($in, $out, &$consumed, $closing)
    {
        while ($bucket = stream_bucket_make_writeable($in)) {
            hash_update($this->context, $bucket->data);

            $consumed += $bucket->datalen;

            stream_bucket_append($out, $bucket);
        }

        return PSFS_PASS_ON;
    }
}

This would be useful when downloading files (PHARs for example, when a hash is likely available)