VOOZH about

URL: https://deepwiki.com/hypervel/filesystem/4.4-streaming-and-content-handling

⇱ Streaming and Content Handling | hypervel/filesystem | DeepWiki


Loading...
Menu

Streaming and Content Handling

This document covers streaming operations for reading and writing files, partial content retrieval through range requests, and HTTP response generation for serving files efficiently. These features enable memory-efficient handling of large files by processing them in chunks rather than loading entire contents into memory.

For information about storing uploaded files, see the upload handling methods in 3.1. For URL generation to access stored files, see 4.3.


Overview

The filesystem abstraction provides comprehensive streaming capabilities that operate efficiently regardless of whether files are stored locally or in cloud storage. All streaming operations return or accept PHP resource handles, maintaining compatibility with standard PHP stream functions.

Sources: src/FilesystemAdapter.php1-867


Stream Reading Operations

Basic Stream Reading

The readStream() method returns a PHP resource handle for reading file contents incrementally without loading the entire file into memory.


The base implementation in FilesystemAdapter delegates to the underlying Flysystem driver and handles exceptions gracefully, returning null on failure if exception throwing is disabled.

Implementation:

src/FilesystemAdapter.php546-555


Range Request Support

The readStreamRange() method enables reading partial file content by specifying byte ranges, which is essential for:

  • HTTP range requests (video/audio streaming)
  • Resumable downloads
  • Efficient preview generation
  • Bandwidth optimization

Method Signature:


The base implementation in FilesystemAdapter throws a RuntimeException as not all drivers support range reads:

src/FilesystemAdapter.php563-566

Sources: src/FilesystemAdapter.php542-566


Driver-Specific Range Implementation

Google Cloud Storage Range Reads

The GoogleCloudStorageAdapter implements full range request support using GCS REST API headers:

src/GoogleCloudStorageAdapter.php89-102


The implementation uses the private readStreamWithOptions() helper to configure the GCS API request with appropriate HTTP range headers. The stream_reads configuration option controls whether responses are streamed or buffered.

Sources: src/GoogleCloudStorageAdapter.php89-127


Stream Writing Operations

Writing from Streams

The writeStream() method accepts a PHP resource handle and writes its contents to the filesystem:

src/FilesystemAdapter.php573-584


Automatic Stream Handling in put()

The put() method automatically detects stream resources and PSR-7 StreamInterface objects, delegating to writeStream():

src/FilesystemAdapter.php307-337

Content TypeHandling
UploadedFileDelegates to putFile() for upload handling
StreamInterfaceExtracts underlying resource via detach()
PHP resourceDirect stream write via writeStream()
StringDirect write via driver->write()

Sources: src/FilesystemAdapter.php307-337 src/FilesystemAdapter.php573-584


HTTP Response Generation

Streamed Response Creation

The response() method generates PSR-7 HTTP responses that stream file content efficiently. This is the primary method for serving files through HTTP:

src/FilesystemAdapter.php242-284

Method Signature:


Parameters:

ParameterDescription
$pathFile path in the filesystem
$nameFilename for Content-Disposition header (defaults to basename)
$headersAdditional HTTP headers to include
$dispositionEither 'inline' (browser display) or 'attachment' (download)

Response Generation Flow


Sources: src/FilesystemAdapter.php242-284


Range Request Handling

When the HTTP request includes a Range header, the response method automatically:

  1. Validates the range using HeaderUtils::validateRangeHeaders()
  2. Adds appropriate headers via withRangeHeaders($fileSize)
  3. Reads partial content using readStreamRange($path, $start, $end)
  4. Returns 206 Partial Content status (handled by response factory)

src/FilesystemAdapter.php262-271


Sources: src/FilesystemAdapter.php242-284


Chunked Streaming Output

The streaming callback reads and outputs the file in configurable chunks (default: 64 KB):

src/FilesystemAdapter.php273-283


Memory Efficiency:

The 64 KB chunk size ensures that even multi-gigabyte files can be served with minimal memory footprint. The stream is automatically closed after transmission completes.

Sources: src/FilesystemAdapter.php273-283


Download Response Helper

The download() method is a convenience wrapper that sets the Content-Disposition header to 'attachment', forcing the browser to download rather than display the file:

src/FilesystemAdapter.php289-292


Sources: src/FilesystemAdapter.php289-292


Streaming Architecture Diagram


Sources: src/FilesystemAdapter.php1-867 src/GoogleCloudStorageAdapter.php1-142


Content Type and Header Management

MIME Type Detection

The response() method automatically detects the MIME type for the Content-Type header:

src/FilesystemAdapter.php248


The mimeType() method delegates to Flysystem's MIME type detection, which typically uses the fileinfo PHP extension.

Content-Disposition Header

The disposition header is constructed using HeaderUtils::makeDisposition(), which properly encodes filenames with special characters and provides ASCII fallbacks:

src/FilesystemAdapter.php252-258


The fallbackName() method generates ASCII-safe filenames for older browsers:

src/FilesystemAdapter.php297-300

Sources: src/FilesystemAdapter.php242-300 src/FilesystemAdapter.php520-531


Driver Support Matrix

FeatureLocalS3GCSFTPSFTP
readStream()
writeStream()
readStreamRange()
response()
download()

Notes:

  • Range Requests: Currently only GoogleCloudStorageAdapter implements readStreamRange(). Other drivers will throw a RuntimeException if range reads are attempted.
  • Response Generation: All drivers support basic response generation, but range requests require driver support.
  • Stream Efficiency: Cloud drivers (S3, GCS) benefit from connection pooling when serving multiple concurrent streams (see 4.1).

Sources: src/FilesystemAdapter.php563-566 src/GoogleCloudStorageAdapter.php89-102


Usage Examples

Serving a File Inline


Forcing Download with Custom Name


Reading Large File in Chunks


Writing from Stream Source


Handling Range Requests (GCS Only)


Sources: src/FilesystemAdapter.php242-292 src/FilesystemAdapter.php546-584 src/GoogleCloudStorageAdapter.php89-102


Performance Considerations

Chunk Size Configuration

The default chunk size of 64 KB balances memory efficiency with I/O performance. This value is hardcoded in the streaming callback:

src/FilesystemAdapter.php273

For specific use cases, consider:

ScenarioRecommended Approach
Many small filesCurrent 64 KB is optimal
Large video filesConsider extending to customize chunk size
Limited memoryCurrent 64 KB is safe
High throughputIncrease chunk size via custom implementation

Stream Resource Management

Streams are automatically closed after transmission completes, preventing resource leaks. The fclose() call is guaranteed to execute even if the client disconnects during streaming.

Connection Pooling for Cloud Streams

When serving files from cloud storage (S3, GCS) in high-concurrency environments, enable connection pooling to reuse HTTP connections across multiple stream operations. See 4.1 for pooling configuration.

Sources: src/FilesystemAdapter.php273-283


Error Handling

Exception Behavior

Stream operations respect the 'throw' configuration option:

ConfigurationBehavior on Error
'throw' => trueThrows Flysystem exceptions
'throw' => falseReturns null or false

src/FilesystemAdapter.php845-848

Range Request Validation

Invalid range requests are handled by HeaderUtils::validateRangeHeaders(), which validates:

  • Byte range format
  • Start position ≤ end position
  • Ranges within file size bounds

Invalid ranges trigger appropriate HTTP error responses.

Sources: src/FilesystemAdapter.php263-266 src/FilesystemAdapter.php845-848

Refresh this wiki

On this page