Web::_socket PHP Method

_socket() protected method

HTTP request via low-level TCP/IP socket
protected _socket ( $url, $options ) : array
$url string
$options array
return array
    protected function _socket($url, $options)
    {
        $eol = "\r\n";
        $headers = [];
        $body = '';
        $parts = parse_url($url);
        $empty = empty($parts['port']);
        if ($parts['scheme'] == 'https') {
            $parts['host'] = 'ssl://' . $parts['host'];
            if ($empty) {
                $parts['port'] = 443;
            }
        } elseif ($empty) {
            $parts['port'] = 80;
        }
        if (empty($parts['path'])) {
            $parts['path'] = '/';
        }
        if (empty($parts['query'])) {
            $parts['query'] = '';
        }
        if ($socket = @fsockopen($parts['host'], $parts['port'], $code, $err)) {
            stream_set_blocking($socket, TRUE);
            stream_set_timeout($socket, isset($options['timeout']) ? $options['timeout'] : ini_get('default_socket_timeout'));
            fputs($socket, $options['method'] . ' ' . $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '') . ' HTTP/1.0' . $eol);
            fputs($socket, implode($eol, $options['header']) . $eol . $eol);
            if (isset($options['content'])) {
                fputs($socket, $options['content'] . $eol);
            }
            // Get response
            $content = '';
            while (!feof($socket) && ($info = stream_get_meta_data($socket)) && !$info['timed_out'] && !connection_aborted() && ($str = fgets($socket, 4096))) {
                $content .= $str;
            }
            fclose($socket);
            $html = explode($eol . $eol, $content, 2);
            $body = isset($html[1]) ? $html[1] : '';
            $headers = array_merge($headers, $current = explode($eol, $html[0]));
            $match = NULL;
            foreach ($current as $header) {
                if (preg_match('/Content-Encoding: (.+)/', $header, $match)) {
                    break;
                }
            }
            if ($match) {
                switch ($match[1]) {
                    case 'gzip':
                        $body = gzdecode($body);
                        break;
                    case 'deflate':
                        $body = gzuncompress($body);
                        break;
                }
            }
            if ($options['follow_location'] && preg_match('/Location: (.+?)' . preg_quote($eol) . '/', $html[0], $loc)) {
                $options['max_redirects']--;
                return $this->request($loc[1], $options);
            }
        }
        return ['body' => $body, 'headers' => $headers, 'engine' => 'socket', 'cached' => FALSE, 'error' => $err];
    }