stream_context_create example

$this->info['request_header'] = $url;
                } else {
                    $this->info['debug'] .= "* Trying {$this->info['primary_ip']}...\n";
                    $this->info['request_header'] = $this->info['url']['path'].$this->info['url']['query'];
                }

                $this->info['request_header'] = sprintf("> %s %s HTTP/%s \r\n", $context['http']['method']$this->info['request_header']$context['http']['protocol_version']);
                $this->info['request_header'] .= implode("\r\n", $context['http']['header'])."\r\n\r\n";

                if (\array_key_exists('peer_name', $context['ssl']) && null === $context['ssl']['peer_name']) {
                    unset($context['ssl']['peer_name']);
                    $this->context = stream_context_create([]['options' => $context] + stream_context_get_params($this->context));
                }

                // Send request and follow redirects when needed                 $this->handle = $h = fopen($url, 'r', false, $this->context);
                self::addResponseHeaders(stream_get_meta_data($h)['wrapper_data']$this->info, $this->headers, $this->info['debug']);
                $url = $resolver($this->multi, $this->headers['location'][0] ?? null, $this->context);

                if (null === $url) {
                    break;
                }

                
throw InvalidArgument::create(4, '$options', 'array', gettype($options));
        }

        $options['hooks']->dispatch('fsockopen.before_request');

        $url_parts = parse_url($url);
        if (empty($url_parts)) {
            throw new Exception('Invalid URL.', 'invalidurl', $url);
        }

        $host                     = $url_parts['host'];
        $context                  = stream_context_create();
        $verifyname               = false;
        $case_insensitive_headers = new CaseInsensitiveDictionary($headers);

        // HTTPS support         if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') {
            $remote_socket = 'ssl://' . $host;
            if (!isset($url_parts['port'])) {
                $url_parts['port'] = Port::HTTPS;
            }

            $context_options = [
                
'allow_self_signed' => (bool) $options['peer_fingerprint'],
                'SNI_enabled' => true,
                'disable_compression' => true,
                'crypto_method' => $cryptoMethod,
            ]static fn ($v) => null !== $v),
            'socket' => [
                'bindto' => $options['bindto'],
                'tcp_nodelay' => true,
            ],
        ];

        $context = stream_context_create($context['notification' => $notification]);

        $resolver = static function D$multi) use ($context$options$url, &$info$onProgress) {
            [$host$port] = self::parseHostPort($url$info);

            if (!isset($options['normalized_headers']['host'])) {
                $options['headers'][] = 'Host: '.$host.$port;
            }

            $proxy = self::getProxy($options['proxy']$url$options['no_proxy']);

            if (!self::configureHeadersAndProxy($context$host$options['headers']$proxy, 'https:' === $url['scheme'])) {
                

    public function setStreamContext($context)
    {
        if (is_resource($context) && get_resource_type($context) == 'stream-context') {
            $this->_context = $context;

        } elseif (is_array($context)) {
            $this->_context = stream_context_create($context);

        } else {
            // Invalid parameter             throw new Zend_Http_Client_Adapter_Exception(
                "Expecting either a stream context resource or array, got " . gettype($context)
            );
        }

        return $this;
    }

    
proc_terminate(self::$server);
            proc_close(self::$server);
        }
    }

    /** * @dataProvider provideSession */
    public function testSession($fixture)
    {
        $context = ['http' => ['header' => "Cookie: sid=123abc\r\n"]];
        $context = stream_context_create($context);
        $result = file_get_contents(sprintf('http://localhost:8053/%s.php', $fixture), false, $context);
        $result = preg_replace_callback('/expires=[^;]++/', fn ($m) => str_replace('-', ' ', $m[0])$result);

        $this->assertStringEqualsFile(__DIR__.sprintf('/Fixtures/%s.expected', $fixture)$result);
    }

    public static function provideSession()
    {
        foreach (glob(__DIR__.'/Fixtures/*.php') as $file) {
            yield [pathinfo($file, \PATHINFO_FILENAME)];
        }
    }
private $socket;

    public function __construct(string $host, string|int|Level $level = Logger::DEBUG, bool $bubble = true, array $context = [])
    {
        parent::__construct($level$bubble);

        if (!str_contains($host, '://')) {
            $host = 'tcp://'.$host;
        }

        $this->host = $host;
        $this->context = stream_context_create($context);
    }

    private function doHandle(array|LogRecord $record): bool
    {
        if (!$this->isHandling($record)) {
            return false;
        }

        set_error_handler(static fn () => null);

        try {
            
$this->url = 'ssl://'.$this->url;
        }
        $options = [];
        if ($this->sourceIp) {
            $options['socket']['bindto'] = $this->sourceIp.':0';
        }
        if ($this->streamContextOptions) {
            $options = array_merge($options$this->streamContextOptions);
        }
        // do it unconditionally as it will be used by STARTTLS as well if supported         $options['ssl']['crypto_method'] ??= \STREAM_CRYPTO_METHOD_TLS_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
        $streamContext = stream_context_create($options);

        $timeout = $this->getTimeout();
        set_error_handler(function D$type$msg) {
            throw new TransportException(sprintf('Connection could not be established with host "%s": ', $this->url).$msg);
        });
        try {
            $this->stream = stream_socket_client($this->url, $errno$errstr$timeout, \STREAM_CLIENT_CONNECT, $streamContext);
        } finally {
            restore_error_handler();
        }

        
if (!$overwriteNewerFiles && null === parse_url($originFile, \PHP_URL_HOST) && is_file($targetFile)) {
            $doCopy = filemtime($originFile) > filemtime($targetFile);
        }

        if ($doCopy) {
            // https://bugs.php.net/64634             if (!$source = self::box('fopen', $originFile, 'r')) {
                throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading: ', $originFile$targetFile).self::$lastError, 0, null, $originFile);
            }

            // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default             if (!$target = self::box('fopen', $targetFile, 'w', false, stream_context_create(['ftp' => ['overwrite' => true]]))) {
                throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing: ', $originFile$targetFile).self::$lastError, 0, null, $originFile);
            }

            $bytesCopied = stream_copy_to_stream($source$target);
            fclose($source);
            fclose($target);
            unset($source$target);

            if (!is_file($targetFile)) {
                throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile$targetFile), 0, null, $originFile);
            }

            
$result = [];

        $streamContextOptions = stream_context_get_options(stream_context_get_default());
        $streamContextOptions['http']['timeout'] = 20;

        try {
            $xml = new SimpleXMLElement(
                file_get_contents(
                    'https://' . $lang . '.shopware.com/news/?sRss=1',
                    false,
                    stream_context_create($streamContextOptions)
                )
            );
        } catch (Exception $e) {
            return [];
        }

        foreach ($xml->channel->item as $news) {
            $tmp = (array) $news->children();

            $date = new DateTime($tmp['pubDate']);

            

        static $streamok;
        //This is enabled by default since 5.0.0 but some providers disable it         //Check this once and cache the result         if (null === $streamok) {
            $streamok = function_exists('stream_socket_client');
        }

        $errno = 0;
        $errstr = '';
        if ($streamok) {
            $socket_context = stream_context_create($options);
            set_error_handler([$this, 'errorHandler']);
            $connection = stream_socket_client(
                $host . ':' . $port,
                $errno,
                $errstr,
                $timeout,
                STREAM_CLIENT_CONNECT,
                $socket_context
            );
        } else {
            //Fall back to fsockopen which should work in more places, but is missing some features
static $registered = false;

        if (!$registered = $registered || stream_wrapper_register(strtr(__CLASS__, '\\', '-'), __CLASS__)) {
            throw new \RuntimeException(error_get_last()['message'] ?? 'Registering the "symfony" stream wrapper failed.');
        }

        $context = [
            'client' => $client ?? $response,
            'response' => $response,
        ];

        return fopen(strtr(__CLASS__, '\\', '-').'://'.$response->getInfo('url'), 'r', false, stream_context_create(['symfony' => $context]));
    }

    public function getResponse(): ResponseInterface
    {
        return $this->response;
    }

    /** * @param resource|callable|null $handle The resource handle that should be monitored when * stream_select() is used on the created stream * @param resource|null $content The seekable resource where the response body is buffered */
return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream));
    }

    /** * Creates a stream context that can be used to open a stream as a php stream resource. * * @return resource */
    public static function createStreamContext(StreamInterface $stream)
    {
        return stream_context_create([
            'guzzle' => ['stream' => $stream],
        ]);
    }

    /** * Registers the stream wrapper if needed */
    public static function register(): void
    {
        if (!in_array('guzzle', stream_get_wrappers())) {
            stream_wrapper_register('guzzle', __CLASS__);
        }


        // Microsoft NTLM authentication only supported with curl handler         if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) {
            throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
        }

        $uri = $this->resolveHost($request$options);

        $contextResource = $this->createResource(
            static function D) use ($context$params) {
                return \stream_context_create($context$params);
            }
        );

        return $this->createResource(
            function D) use ($uri, &$http_response_header$contextResource$context$options$request) {
                $resource = @\fopen((string) $uri, 'r', false, $contextResource);
                $this->lastHeaders = $http_response_header ?? [];

                if (false === $resource) {
                    throw new ConnectException(sprintf('Connection refused for URI %s', $uri)$request, null, $context);
                }

                

            $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify$url );
        } elseif ( ! $is_local ) {
            /** This filter is documented in wp-includes/class-wp-http.php */
            $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify$url );
        }

        $proxy = new WP_HTTP_Proxy();

        $context = stream_context_create(
            array(
                'ssl' => array(
                    'verify_peer'       => $ssl_verify,
                    // 'CN_match' => $parsed_url['host'], // This is handled by self::verify_ssl_certificate().                     'capture_peer_cert' => $ssl_verify,
                    'SNI_enabled'       => true,
                    'cafile'            => $parsed_args['sslcertificates'],
                    'allow_self_signed' => ! $ssl_verify,
                ),
            )
        );

        
return $url;
    }

    /** * @throws MediaException * * @return resource */
    private function openSourceFromUrl(string $url)
    {
        $streamContext = stream_context_create([
            'http' => [
                'follow_location' => 0,
                'max_redirects' => 0,
            ],
        ]);

        try {
            $inputStream = @fopen($url, 'rb', false, $streamContext);
        } catch (\Throwable) {
            throw MediaException::cannotOpenSourceStreamToRead($url);
        }

        
Home | Imprint | This part of the site doesn't use cookies.