cli curl成功; php-libcurl调用失败

时间:2014-01-25 03:42:17

标签: php macos curl

在Mac OS 10.9.1上使用PHP 5.4.17和curl 7.30.0,这个curl请求在命令行运行正常:

curl -u test:test http://localhost/protected/

但是这个使用curl库的PHP脚本失败了:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/protected/');
curl_setopt($ch, CURLOPT_HTTPAUTH, 'CURLAUTH_BASIC');
curl_setopt($ch, CURLOPT_USERPWD, 'test:test');
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
echo curl_exec($ch);
curl_close($ch);

输出结果为:

$ php -e ./test.php 
* Adding handle: conn: 0x7fe1b303de00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fe1b303de00) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 80 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 80 (#0)
> GET /protected/ HTTP/1.1
Host: localhost
Accept: */*

< HTTP/1.1 401 Authorization Required
< Date: Sat, 25 Jan 2014 03:12:40 GMT
* Server Apache/2.2.24 (Unix) DAV/2 PHP/5.4.17 mod_ssl/2.2.24 OpenSSL/0.9.8y is not blacklisted
< Server: Apache/2.2.24 (Unix) DAV/2 PHP/5.4.17 mod_ssl/2.2.24 OpenSSL/0.9.8y
< WWW-Authenticate: Basic realm="Restricted Files"
< Content-Length: 401
< Content-Type: text/html; charset=iso-8859-1
<
[...]

请注意,请求标头中缺少“授权:基本...”行。如果我手动设置这样的请求标题,它可以正常工作:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(base64_encode('test:test')));

使用PHP 5.4.11和curl 7.21.4运行Mac OS 10.7.5的旧系统正确发送Authorization标头。我尝试了许多不同的PHP组合(5.4.11,5.4.17,5.4.24,5.5.8)和curl(7.30.0,7.30.4),但在Mac OS 10.9.1上,他们都没有发送除非我手动设置授权标头。为什么?

1 个答案:

答案 0 :(得分:0)

这是错误的:

curl_setopt($ch, CURLOPT_HTTPAUTH, 'CURLAUTH_BASIC');
                                   ^--            ^--

使用引号,您尝试将字符串设置为选项。但CURL使用define()'d常量,这些常量未引用。

尝试

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

所以你使用的是实际的CURL常量,而不是像L常量那样发生在LOOK上的随机字符串。