bhylu.com

Advertisements

PHP Streams Reference

Streams unify several kinds of input/output, but a shared API does not make all stream sources equally trusted or rewindable.

How it works

A local file, memory stream and remote wrapper can have different blocking, seek and permission behaviour. Context options apply only to the wrappers that support them. Always distinguish end-of-stream from an operation failure, cap reads and close owned handles. Do not enable arbitrary wrappers through a user-controlled path just because fopen accepts a string.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l ref-streams.php
php ref-streams.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · ref-streams.php

<?php
declare(strict_types=1);

$handle = fopen("php://memory","w+");
if ($handle === false) throw new RuntimeException("No stream");
try {
    fwrite($handle,"ABCDEF"); rewind($handle);
    echo stream_get_contents($handle,3), "\n";
    echo ftell($handle), " byte position\n";
} finally { fclose($handle); }

Expected result

ABC
3 byte position

The bounded read consumes three bytes and advances the position. A different stream might not support seeking or might block while waiting for input. The current private memory fixture is deterministic, not proof of a remote wrapper’s timeout or size behaviour.

Contracts to check

API or termImportant boundary
stream_get_contents, stream_copy_to_streamBound the amount of data and handle failures.
stream_context_create, stream_context_set_optionOptions are wrapper-specific, not a universal transport policy.
stream_get_meta_data, stream_get_wrappersInspect capabilities rather than assuming every source behaves like a file.
fseek, ftell, rewind, feofPosition, end state and failure state are distinct.

Check the official PHP manual for detailed version and API contracts.