3

I am trying to make a CURL request with some basic authentication (through sending an encrypted header). However, when I try to set the "Host: _" header, the remote server responds with:

Bad Request: Your browser sent a request that this server could not understand.

Here's the code that makes the CURL call. Note that it works as soon as I comment out the "Host: url" header in the $http_header variable. However, it is used on the target server as part of the authentication procedure, so I can not simply remove it.

    $curl = curl_init();

    $opt = array(
        CURLOPT_URL=>$url,
        CURLOPT_RETURNTRANSFER=>1,
        CURLOPT_HTTPHEADER=>$http_header,
        CURLOPT_POST=>1,
        CURLOPT_POSTFIELDS=>$data_params,
        CURLOPT_CONNECTTIMEOUT=>5, // Timeout to 5 seconds
    );
    curl_setopt_array($curl, $opt);

    // $output contains the output string
    $output = curl_exec($curl);

    // it closes the session
    curl_close($curl);

The contents of $http_header (an associative array):

array
  0 => string 'Host: http://localhost/work/myproject'
  1 => string 'Content-Type: multipart/form-data'
  2 => string 'X-Authorization: Basicauth Z2xZjA2YzJhMzIxYTI1ZmIzZTgxYQ=='
4

4 回答 4

3

Host头不接受完整的 URL,而只接受主机名。

在这种情况下,解决方案是替换此标头:

"Host: $url"

和:

"Host: ". parse_url($url, PHP_URL_HOST) ."
于 2013-02-20T11:57:24.127 回答
2

Host头采用主机名,而不是 URL。即localhost,不是http://localhost/work/myproject

cURL 应该会自动生成它CURLOPT_URL

于 2013-02-20T10:55:06.937 回答
1

Host头不应包含协议,仅包含主机名。因此,在这种情况下,您只需要localhost

'Host: localhost'
于 2013-02-20T10:55:04.877 回答
1

我认为这两个答案都不能回答提问者的问题。我遇到了同样的问题。通过查看 cURL 发送的内容,它正在发送自己的 Host 标头。这意味着当您添加一个时,您现在有两个。当所有服务器看到多个主机头时,它们必须以 400 错误响应。

诀窍是让 cURL 不生成它自己的标题(我还没有弄清楚如何去做)或者不发送你的。在你的情况下,似乎不发送你的很好。但是,对于我正在做的事情,我必须发送我的。

于 2015-08-08T15:50:17.633 回答