PHP Context Parameters

Context parameters allow customization of access to filesystem and other stream wrappers. To configure a stream, PHP has stream_context_set_params() function.

Syntax

stream_context_set_params ( resource $stream_or_context , array $params ) : bool

Parameters:

  • $stream_or_context − Any of PHP's supported streams/wrappers/contexts
  • $params − An associative array of the structure $params['paramname'] = "paramvalue"

Context Parameters

notification − A user-defined callback to be called whenever a stream triggers a notification. Only for http:// and ftp:// stream wrappers.

The notification callback function has the following syntax:

stream_notification_callback ( 
    int $notification_code, 
    int $severity, 
    string $message, 
    int $message_code, 
    int $bytes_transferred, 
    int $bytes_max 
) : void

options − Array of supported options corresponding to context/wrapper in use.

Example

Here's how to set up a notification callback for monitoring HTTP requests ?

<?php
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    switch($notification_code) {
        case STREAM_NOTIFY_RESOLVE:
            echo "Resolving...<br>";
            break;
        case STREAM_NOTIFY_CONNECT:
            echo "Connected...<br>";
            break;
        case STREAM_NOTIFY_PROGRESS:
            echo "Progress: $bytes_transferred/$bytes_max<br>";
            break;
    }
}

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
$content = file_get_contents("http://php.net/contact", false, $ctx);
?>

Setting Multiple Parameters

You can set multiple parameters at once ?

<?php
$ctx = stream_context_create();

// Set multiple parameters
$params = array(
    "notification" => function($code, $severity, $message) {
        echo "Notification: $message<br>";
    },
    "options" => array(
        "http" => array(
            "timeout" => 10,
            "user_agent" => "My Custom Agent"
        )
    )
);

$result = stream_context_set_params($ctx, $params);
var_dump($result); // Returns true on success
?>

Conclusion

The stream_context_set_params() function provides fine-grained control over stream behavior, particularly useful for monitoring HTTP/FTP operations and customizing stream options.

Updated on: 2026-03-15T09:21:45+05:30

590 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements