ParagonIE\Halite\Stream\ReadOnlyFile::readBytes PHP Method

readBytes() public method

Read from a stream; prevent partial reads (also uses run-time testing to prevent partial reads -- you can turn this off if you need performance and aren't concerned about race condition attacks, but this isn't a decision to make lightly!)
public readBytes ( integer $num, boolean $skipTests = false ) : string
$num integer
$skipTests boolean Only set this to TRUE if you're absolutely sure that you don't want to defend against TOCTOU / race condition attacks on the filesystem!
return string
    public function readBytes(int $num, bool $skipTests = false) : string
    {
        if ($num < 0) {
            throw new CryptoException\CannotPerformOperation('num < 0');
        } elseif ($num === 0) {
            return '';
        }
        if ($this->pos + $num > $this->stat['size']) {
            throw new CryptoException\CannotPerformOperation('Out-of-bounds read');
        }
        $buf = '';
        $remaining = $num;
        if (!$skipTests) {
            $this->toctouTest();
        }
        do {
            if ($remaining <= 0) {
                break;
            }
            $read = \fread($this->fp, $remaining);
            if ($read === false) {
                throw new CryptoException\FileAccessDenied('Could not read from the file');
            }
            $buf .= $read;
            $readSize = CryptoUtil::safeStrlen($read);
            $this->pos += $readSize;
            $remaining -= $readSize;
        } while ($remaining > 0);
        return $buf;
    }

Usage Example

Beispiel #1
0
 public function testFileRead()
 {
     $filename = \tempnam('/tmp', 'x');
     $buf = \Sodium\randombytes_buf(65537);
     \file_put_contents($filename, $buf);
     $fStream = new ReadOnlyFile($filename);
     $this->assertSame($fStream->readBytes(65537), $buf);
     $fStream->reset(0);
     \file_put_contents($filename, Util::safeSubstr($buf, 0, 32768) . 'x' . Util::safeSubstr($buf, 32768));
     try {
         $fStream->readBytes(65537);
         throw new \Exception('fail');
     } catch (CryptoException\FileModified $ex) {
         $this->assertTrue($ex instanceof CryptoException\FileModified);
     }
 }
All Usage Examples Of ParagonIE\Halite\Stream\ReadOnlyFile::readBytes