Back to Stream class

Method read

public mixed
read
(mixed $length = 0)
Read a file
Parameters
  • int $length Length of data to read
Returns
  • mixed
Since
  • 1.7.0
-
  • https://www.php.net/manual/en/function.fread.php
Class: Stream
Project: Joomla

Method read - Source code

/**
 * Read a file
 *
 * Handles user space streams appropriately otherwise any read will return 8192
 *
 * @param   integer  $length  Length of data to read
 *
 * @return  mixed
 *
 * @link    https://www.php.net/manual/en/function.fread.php
 * @since   1.7.0
 */
public function read($length = 0)
{
    if (!$this->filesize && !$length) {
        // Get the filesize
        $this->filesize();
        if (!$this->filesize) {
            // Set it to the biggest and then wait until eof
            $length = -1;
        } else {
            $length = $this->filesize;
        }
    }
    if (!$this->fh) {
        $this->setError(Text::_('JLIB_FILESYSTEM_ERROR_STREAMS_FILE_NOT_OPEN'));
        return false;
    }
    $retval = false;
    // Capture PHP errors
    $php_errormsg = 'Error Unknown';
    $track_errors = ini_get('track_errors');
    ini_set('track_errors', true);
    $remaining = $length;
    do {
        // Do chunked reads where relevant
        switch ($this->processingmethod) {
            case 'bz':
                $res = $remaining > 0 ? bzread($this->fh, $remaining) : bzread($this->fh, $this->chunksize);
                break;
            case 'gz':
                $res = $remaining > 0 ? gzread($this->fh, $remaining) : gzread($this->fh, $this->chunksize);
                break;
            case 'f':
            default:
                $res = $remaining > 0 ? fread($this->fh, $remaining) : fread($this->fh, $this->chunksize);
                break;
        }
        if (!$res) {
            $this->setError($php_errormsg);
            // Jump from the loop
            $remaining = 0;
        } else {
            if (!$retval) {
                $retval = '';
            }
            $retval .= $res;
            if (!$this->eof()) {
                $len = \strlen($res);
                $remaining -= $len;
            } else {
                // If it's the end of the file then we've nothing left to read; reset remaining and len
                $remaining = 0;
                $length = \strlen($retval);
            }
        }
    } while ($remaining || !$length);
    // Restore error tracking to what it was before
    ini_set('track_errors', $track_errors);
    // Return the result
    return $retval;
}