Defuse\Crypto\File::writeBytes PHP Method

writeBytes() public static method

Write to a stream; prevents partial writes.
public static writeBytes ( resource $stream, string $buf, integer $num_bytes = null ) : string
$stream resource
$buf string
$num_bytes integer
return string
    public static function writeBytes($stream, $buf, $num_bytes = null)
    {
        $bufSize = Core::ourStrlen($buf);
        if ($num_bytes === null) {
            $num_bytes = $bufSize;
        }
        if ($num_bytes > $bufSize) {
            throw new Ex\IOException('Trying to write more bytes than the buffer contains.');
        }
        if ($num_bytes < 0) {
            throw new Ex\IOException('Tried to write less than 0 bytes');
        }
        $remaining = $num_bytes;
        while ($remaining > 0) {
            $written = \fwrite($stream, $buf, $remaining);
            if ($written === false) {
                throw new Ex\IOException('Could not write to the file');
            }
            $buf = Core::ourSubstr($buf, $written, null);
            $remaining -= $written;
        }
        return $num_bytes;
    }

Usage Example

 /**
  * Returns a stream representation of a string.
  *
  * @param string $contents The string
  *
  * @return resource The stream with the string contents.
  */
 private function getStreamFromString($contents)
 {
     $resource = fopen('php://memory', 'r+b');
     File::writeBytes($resource, $contents);
     rewind($resource);
     return $resource;
 }
All Usage Examples Of Defuse\Crypto\File::writeBytes