【问题标题】:php sending http headersphp发送http头
【发布时间】:2011-10-19 16:04:27
【问题描述】:

我使用 php 函数 file_get_contents,其中一个参数是 http 标头。我把它们做成这样:

if (strpos($key, 'HTTP_') === 0) {
    $key = strtolower(strtr(substr($key, 5), '_', '-'));
    $this->headers .= $key . ': ' . $value . '\r\n';
}

但这里有个问题,我应该像这样用双引号发送标题:

"Connection: close\r\nContent-Length: $data_len\r\n"

这是我如何提出请求的示例:

$opts = array(
        'http'  =>  array(
            'method'    => "GET",
            'header'    => $this->headers
        )
);

$this->data = file_get_contents('http://phd.yandex.net/detect', false, stream_context_create($opts));

但它失败了。如果我用自定义的 http 标头字符串替换数组中的 $this->headers,一切正常。

如何让它正常工作?

【问题讨论】:

  • 你考虑过cURL吗?
  • 你的自定义字符串是什么样的,v.s.上面的代码生成了什么?
  • 你省略了\r\n周围的引号是错字吗?
  • 您在第一个代码部分中缺少 \r\n 周围的引号 - 这可能是问题吗?我怀疑它不会解析,但你永远不知道......
  • \r\n 周围缺少引号,这是一个错字

标签: php http http-headers


【解决方案1】:

\r\n 需要在 双引号 中,以便正确解析字符。其他所有内容都可以使用单引号附加,没问题。使用单引号字符串中的反斜杠仅解析少数内容,例如\\\'\"

您的标题如下所示:

Key: Value\r\nKey: value\r\n

\r\n 显示为实际字符串的位置,当您希望它看起来像这样时:

Key: Value
Key: Value

\r\n 实际上在标题中创建了一个新行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2022-11-18
    • 2021-10-21
    • 2012-01-09
    相关资源
    最近更新 更多