Get Stream Errors using stream_last_errors in PHP 8.6

Get Stream Errors using stream_last_errors in PHP 8.6

Since PHP 8.6, a new stream_last_errors function returns the errors of the last failed stream operation. Each error is a StreamError object. Before PHP 8.6, the reason of a failure was available only as a warning message, which had to be caught by an error handler and parsed.

The following code tries to open a file which does not exist and prints details about the error:

<?php

$context = stream_context_create(
    ['stream' => ['error_mode' => StreamErrorMode::Silent]],
);

$handle = fopen('missing.txt', 'rb', false, $context);
if ($handle === false) {
    $error = stream_last_errors()[0];

    echo $error->code->name.': '.$error->message.' ('.$error->wrapperName.')';
}

Output:

OpenFailed: Failed to open stream: No such file or directory (plainfile)

The error_mode stream context option controls how a failure is reported. The StreamErrorMode::Silent value suppresses the warning and keeps the error available for stream_last_errors. Without this option, the warning is emitted as before and stream_last_errors returns an empty array. To keep the warning and still collect the errors, the error_store option must be set to StreamErrorStore::All.

The StreamError object has five readonly properties:

  • code - a StreamErrorCode enum, which describes the kind of failure, such as OpenFailed.
  • message - describes the failure. It is the warning text without the function name prefix.
  • wrapperName - the name of the stream wrapper, which is plainfile for local files.
  • severity - the error level, such as 2 for E_WARNING.
  • terminating - shows whether the error ended the operation.

Since PHP 8.6, there is also a new stream_clear_errors function which removes all stored errors.

Leave a Comment

Cancel reply

Your email address will not be published.