dongpuchao1680
2015-04-28 08:15
浏览 127
已采纳

PHP脚本中cURL请求的奇怪行为

I'm experiencing weird behaviour of a cURL request that I do in my PHP code. I'm running the code locally on a standard WAMP Apache server. Here's the code:

$auth_info = "...";
$some_url = "...";
$channel = curl_init();
curl_setopt($channel, CURLOPT_URL, $some_url);
curl_setopt($channel, CURLOPT_HTTPHEADER, 
    array("Authorization: BASIC " . base64_encode($auth_info))
);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
curl_setopt($channel, CURLOPT_HEADER, true);
$response = curl_exec($channel);
var_dump(curl_getinfo($channel));
$header_size = curl_getinfo($channel, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
var_dump($header);
var_dump($body);
curl_close($channel);

If I'm executing this little PHP code snippet via my CLI (Powershell, since I'm running on Windows), everything is fine, all var_dumps work and I can see the $header and $body and everything and the data I expect is actually present.

Now for the weird behaviour. If I'm opening the script file with the above snippet in any browser, it just gives me:

array (size=26)
'url' => string 'the_url_here' (length=39)
'content_type' => null
'http_code' => int 0
'header_size' => int 0
'request_size' => int 0
'filetime' => int -1
'ssl_verify_result' => int 0
'redirect_count' => int 0
'total_time' => float 1.234
'namelookup_time' => float 0
'connect_time' => float 0.109
'pretransfer_time' => float 0
'size_upload' => float 0
'size_download' => float 0
'speed_download' => float 0
'speed_upload' => float 0
'download_content_length' => float -1
'upload_content_length' => float -1
'starttransfer_time' => float 0
'redirect_time' => float 0
'redirect_url' => string '' (length=0)
'primary_ip' => string 'here_is_the_ip' (length=12)
'certinfo' => 
  array (size=0)
    empty
'primary_port' => int 443
'local_ip' => string 'here_is_my_ip' (length=13)
'local_port' => int -> my_local_port_here
boolean false
boolean false

I'm completely puzzled since I cannot see a difference between the script beeing started by the CLI and beeing started by the browser. Has anyone got an idea on this?

EDIT Note: If I'm using Guzzle for the request, everything works fine, both in CLI and browser. I'm still interested in an answer why cURL is causing problems here.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpb56083 2015-04-29 08:26
    已采纳

    Have you tried logging verbose output for the Curl request?

    Normally I find this the best way to figure out what's going on under the hood...https://stackoverflow.com/a/14436877/682754

    Also not as popular but this approach looks simple to implement and is a lot cleaner...https://stackoverflow.com/a/26611776/682754

    已采纳该答案
    打赏 评论