如何使原始的HTTP请求时轻松解码HTTP-分块编码字符串?(How to easily decod

2019-06-25 09:03发布

我想使HTTP请求,而不必依赖于卷曲和allow_url_fopen = 1通过打开套接字连接,并发送原始的HTTP请求:

/**
 * Make HTTP GET request
 *
 * @param   string   the URL
 * @param   int      will be filled with HTTP response status code
 * @param   string   will be filled with HTTP response header
 * @return  string   HTTP response body
 */
function http_get_request($url, &$http_code = '', &$res_head = '') 
{
  $scheme = $host = $user = $pass = $query = $fragment = '';
  $path = '/';
  $port = substr($url, 0, 5) == 'https' ? 443 : 80;

  extract(parse_url($url)); 

  $path .= ($query ? "?$query" : '').($fragment ? "#$fragment" : '');

  $head = "GET $path HTTP/1.1\r\n"
        . "Host: $host\r\n"
        . "Authorization: Basic ".base64_encode("$user:$pass")."\r\n"
        . "Connection: close\r\n\r\n";

  $fp = fsockopen($scheme == 'https' ? "ssl://$host" : $host, $port) or 
    die('Cannot connect!');

  fputs($fp, $head);
  while(!feof($fp)) {
    $res .= fgets($fp, 4096);
  }
  fclose($fp);

  list($res_head, $res_body) = explode("\r\n\r\n", $res, 2);
  list(, $http_code, ) = explode(' ', $res_head, 3);

  return $res_body;
}

该功能工作正常,但由于我使用HTTP / 1.1,响应主体通常在返回的分块编码字符串。 例如(维基百科):

25
This is the data in the first chunk

1C
and this is the second one

3
con
8
sequence
0

我不想用http_chunked_decode()因为它具有PECL依赖,我想一个高度可移植的代码。

如何轻松解码HTTP-分块编码字符串,所以我的函数可以返回原来的HTML? 我还必须确保已解码的字符串匹配的长度Content-Length:头。

任何帮助,将不胜感激。 谢谢。

Answer 1:

由于该函数返回的HTTP响应头,你应该检查'Transfer-Encoding''chunked'然后解码分块编码字符串。 在伪代码:

CALL parse_http_header
IF 'Transfer-Encoding' IS 'chunked'
  CALL decode_chunked

解析HTTP响应报头:

下面是HTTP响应报头解析到关联数组的功能。

function parse_http_header($str) 
{
  $lines = explode("\r\n", $str);
  $head  = array(array_shift($lines));
  foreach ($lines as $line) {
    list($key, $val) = explode(':', $line, 2);
    if ($key == 'Set-Cookie') {
      $head['Set-Cookie'][] = trim($val);
    } else {
      $head[$key] = trim($val);
    }
  }
  return $head;
}

该函数会返回一个这样的数组:

Array
(
    [0] => HTTP/1.1 200 OK
    [Expires] => Tue, 31 Mar 1981 05:00:00 GMT
    [Content-Type] => text/html; charset=utf-8
    [Transfer-Encoding] => chunked
    [Set-Cookie] => Array
        (
            [0] => k=10.34; path=/; expires=Sat, 09-Jun-12 01:58:23 GMT; domain=.example.com
            [1] => guest_id=v1%3A13; domain=.example.com; path=/; expires=Mon, 02-Jun-2014 13:58:23 GMT
        )
    [Content-Length] => 43560
)

注意如何Set-Cookie头解析为数组。 以后需要分析该cookie到URL关联与饼干需要发送。


解码分块编码的字符串

下面的函数采取分块编码的字符串作为参数,并返回已解码的字符串。

function decode_chunked($str) {
  for ($res = ''; !empty($str); $str = trim($str)) {
    $pos = strpos($str, "\r\n");
    $len = hexdec(substr($str, 0, $pos));
    $res.= substr($str, $pos + 2, $len);
    $str = substr($str, $pos + 2 + $len);
  }
  return $res;
}

// Given the string in the question, the function above will returns:
//
// This is the data in the first chunk
// and this is the second one
// consequence


Answer 2:

我不知道,如果它是最适合你,你需要做什么,但如果指定HTTP/1.0 ,而不是HTTP/1.1 ,你不会得到一个分块响应。



Answer 3:

在WordPress的这个功能的使用。

function decode_chunked($data) {
    if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data))) {
        return $data;
    }



    $decoded = '';
    $encoded = $data;

    while (true) {
        $is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches);
        if (!$is_chunked) {
            // Looks like it's not chunked after all
            return $data;
        }

        $length = hexdec(trim($matches[1]));
        if ($length === 0) {
            // Ignore trailer headers
            return $decoded;
        }

        $chunk_length = strlen($matches[0]);
        $decoded .= substr($encoded, $chunk_length, $length);
        $encoded = substr($encoded, $chunk_length + $length + 2);

        if (trim($encoded) === '0' || empty($encoded)) {
            return $decoded;
        }
    }

    // We'll never actually get down here
    // @codeCoverageIgnoreStart
}


文章来源: How to easily decode HTTP-chunked encoded string when making raw HTTP request?
标签: php http