Current Location: Home> Function Categories> stream_context_create

stream_context_create

Create resource flow context
Name:stream_context_create
Category:Stream
Programming Language:php
One-line Description:Create a stream context

Function name: stream_context_create()

Function function: Create a stream context

Applicable versions: All versions

Function usage: stream_context_create ( array $options = ? , array $params = ? ) : resource

Parameter description:

  • options: an associative array that sets the options for stream context. Optional parameters include:

    • http: Options used to set HTTP requests, such as method, header, content, etc.
    • ssl: Options for setting SSL/TLS connections, such as verify_peer, cafile, ciphers, etc.
    • ftp: Options used to set FTP connections, such as overwrite, resume_pos, etc.
    • socket: Options used to set socket connections, such as bindto, backlog, etc.
  • params: an associative array that sets additional parameters for the stream context. Optional parameters include:

    • notification: A callback function used to handle notification events in the stream context, such as transmission progress, errors, etc.

Return value: Returns a resource type stream context when successful, and returns false when failure.

Sample code:

 // 创建一个HTTP请求的流上下文$options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode(array('name' => 'John')), ), ); $context = stream_context_create($options); // 发送HTTP请求$response = file_get_contents('http://example.com/api', false, $context); // 创建一个SSL连接的流上下文$options = array( 'ssl' => array( 'verify_peer' => true, 'cafile' => '/path/to/cert.pem', ), ); $context = stream_context_create($options); // 打开一个SSL连接$socket = stream_socket_client('ssl://example.com:443', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context); if (!$socket) { die("Failed to connect: $errstr ($errno)"); } // 其他用法和示例请参考官方文档:https://www.php.net/manual/en/function.stream-context-create.php

Notes:

  • The stream_context_create() function can be used to create various types of stream contexts, such as HTTP requests, SSL connections, FTP connections, etc.
  • The options parameter is an associative array, and different options can be set according to specific needs.
  • The params parameter is an associative array that is used to set additional parameters such as notification callback functions.
  • After successful creation, the stream context can be passed as a parameter to other stream-related functions, such as file_get_contents(), stream_socket_client(), etc.
  • For more detailed usage and examples, please refer to the official PHP documentation.
Similar Functions
Popular Articles