Read File in Chunks

This greatly reduces overhead if serving files through a PHP
gateway script.

@param string $file Path.
@param bool $retbytes Return bytes served like `readfile()`.
@return mixed Bytes served or status.
556603
public static function readfile_chunked(string $file, bool $retbytes=true) {
		if (! $file || ! @\is_file($file)) {
			return false;
		}

		$buffer = '';
		$cnt = 0;
		$chunk_size = 1024 * 1024;

		if (false === ($handle = @\fopen($file, 'rb'))) {
			return false;
		}

		while (! @\feof($handle)) {
			$buffer = @\fread($handle, $chunk_size);
			echo $buffer;
			\ob_flush();
			\flush();
			if ($retbytes) {
				$cnt += \strlen($buffer);
			}
		}

		$status = @\fclose($handle);

		// Return number of bytes delivered like readfile() does.
		if ($retbytes && $status) {
			return $cnt;
		}

		return $status;
	}
717395
public function read($bytesRequested)
    {
        if($this->_currentPart >= count($this->_parts)) {
          return FALSE;
        }

        $activePart = $this->_parts[$this->_currentPart];
        $buffer = $activePart->read($bytesRequested);

        while(strlen($buffer) < $bytesRequested) {
          $this->_currentPart += 1;
          $nextBuffer = $this->read($bytesRequested - strlen($buffer));
          if($nextBuffer === FALSE) {
            break;
          }
          $buffer .= $nextBuffer;
        }

        return $buffer;
    }
1142250
public function realPath($file)
    {
        $path = parent::realPath($file);

        if($base = $this->getBasePath())
        {
            if(strpos($file, $base) !== 0) {
                return false;
            }
        }

        return $path;
    }
939299
protected function read($file)
    {
        $data = null;
        $key  = $file;
        $file = $this->getFileName($file);

        if ( file_exists($file))
        {
            // if cache file not expire
            if (filemtime($file) >= time())
            {
                echo "read cache<br/>";
                $data = file_get_contents($file);
                $data = ($this->base64Encode) ? base64_decode($data) : $data;
                $data = unserialize($data);
                static::$keys[$key] = true;
            }
            else
            {
                unset(static::$keys[$key]);
                unlink($file);
            }
        }

        return $data;
    }
1231881
private function readBytes($bytes, $noBuffer)
    {
        if(!$this->socket) {
            return "";
        }

        if($noBuffer) {
            return fread($this->socket, $bytes);
        }

        $bytes_left = $bytes;
        $retval = "";
        while( !feof($this->socket) && $bytes_left > 0 ) {
            $res = fread($this->socket, $bytes_left);
            $retval.=$res;
            $bytes_left-=strlen($res);
        }

        return $retval;
    }
594580
public static function downloadStatic($file, $headers = array()) {

        if (!is_array($headers)) {
            $headers = array();
        }

        $headers = array_merge(array(
            'Content-Type' => 'application/octet-stream'
        ), $headers);

        $respone = new BinaryFileResponse(
            $file,
            $status = 200,
            $headers,
            $public = true,
            $contentDisposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            $autoEtag = true,
            $autoLastModified = true
        );

        return $respone;
    }
1175681
public static function read($file)
    {
        if (!is_readable($file)) {
            return;
        }
        $data = @file_get_contents($file);
        if ($data === false) {
            return;
        }
        $value = @unserialize($data);
        if ($value === false) {
            return;
        }

        return $value;
    }
593180
protected byte[] loadBinaryFile(String file) throws IOException {
        try (InputStream is = resource.getInputStream(file)) {
            return IOUtils.toByteArray(is);
        }
    }
1194011
function read($inByte = null)
    {
        $this->_assertReadable();

        $inByte = ($inByte === null)
            ?
            (
                ($this->getBuffer() === null) ? -1 : $this->getBuffer()
            )
            : $inByte;

        $stream = $this->resource()->getRHandler();
        $data   = stream_get_contents($stream, $inByte);
        if (false === $data)
            throw new \RuntimeException('Cannot read stream.');

        if (function_exists('mb_strlen'))
            $transCount = mb_strlen($data, '8bit');
        else
            $transCount = strlen($data);

        $this->_resetTransCount($transCount);

        return $data;
    }
227246
function file_get_contents($file)
		{
			$fd = fopen($file, 'rb');
			$content = fread($fd, filesize($file));
			fclose($fd);
			$this->file_loaded_size+= strlen($content);
			return $content;				
		}
784127
public static function deserializeFromFile($file)
  {
    if (file_exists($file))
    {
      $serialized_data = file_get_contents($file);
      return unserialize($serialized_data);
    }
    else return null;
  }
71637
public function readFile(
        string $fileName,
        bool $removeEmptyElements = true,
        int $retries = 0,
        int $retryPause = 250
    ) {
        $fileName = $this->file->determineFilePath($fileName);

        $this->logger->debug(sprintf('File path for filename: %s', $fileName));

        if (is_file($fileName)) {

            $this->logger->debug('Convert XML to array');

            $data = $this->simpleXmlLoadFile($fileName, $retries, $retryPause);

            if ($data !== false) {
                $data = json_decode(json_encode((array)$data), true);

                if ($removeEmptyElements) {
                    $data = $this->arrays->arrayFilterRecursive($data);
                }
            }

            return $data;
        } else {
            throw new \Exception(sprintf('Could not read file: %s because: Not a file', $fileName));
        }
    }
1295783
public function forceDownload($file)
    {
        session_write_close();
        ob_clean();
        header('Content-type: application/octet-stream');
        $filename = basename($file);
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header('Content-Length: ' . filesize($file));
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Transfer-Encoding: binary");
        header("Content-Encoding: plainbinary");

        // This code isn't ready yet. It will allow us to no longer force download

        /*
        $h = Core::make('helper/mime');
        $mimeType = $h->mimeFromExtension($this->getExtension($file));
        header('Content-type: ' . $mimeType);
        */

        $buffer = '';
        $chunk = 1024 * 1024;
        $handle = fopen($file, 'rb');
        if ($handle === false) {
            return false;
        }
        while (!feof($handle)) {
            $buffer = fread($handle, $chunk);
            echo $buffer;
        }

        fclose($handle);
        exit;
    }
356216
def read_bytes(self, path):
        """"""
        file = staticfiles_storage.open(path)
        content = file.read()
        file.close()
        return content
187730
public static byte[] readFile(File file) throws IOException
    {
        //create stream to file
        InputStream inputStream=new FileInputStream(file);

        //read data
        byte[] data=IOHelper.readStream(inputStream);

        return data;
    }
919516
private static byte[] readBytes(final File aFile) throws IOException {
        final FileInputStream fileStream = new FileInputStream(aFile);
        final ByteBuffer buf = ByteBuffer.allocate((int) aFile.length());
        final int read = fileStream.getChannel().read(buf);

        if (read != aFile.length()) {
            fileStream.close();
            throw new IOException(LOGGER.getI18n(MessageCodes.UTIL_044, aFile));
        }

        fileStream.close();
        return buf.array();
    }
41740
public function loadFile($file)
    {
        $openfile = @fopen($file, "rb") or die("loadFile: Error opening file '{$file}'.");
        $contents = @fread($openfile, filesize($file)) or die("loadFile: Error reading data from file '{$file}'.");
        @fclose($openfile);
        return $contents;
    }