3

cURLに依存せずに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 依存関係があり、移植性の高いコードが必要なため、使用したくありません。

関数が元の HTML を返すことができるように、HTTP チャンクでエンコードされた文字列を簡単にデコードする方法は? Content-Length:また、デコードされた文字列の長さがヘッダーと一致することを確認する必要があります。

どんな助けでも大歓迎です。ありがとう。

4

3 に答える 3

12

この関数は 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 を関連付けるために、後で Cookie を解析する必要があります。


チャンクエンコードされた文字列をデコードする

以下の関数は、チャンクエンコードされた文字列を引数として取り、デコードされた文字列を返します。

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
于 2012-06-02T02:45:06.410 に答える
2

何をする必要があるかはわかりませんが、のHTTP/1.0代わりに指定するHTTP/1.1と、チャンクされた応答は得られません。

于 2012-05-29T04:24:34.743 に答える