【问题标题】:cli curl succeeds; php-libcurl invocation failscli curl 成功; php-libcurl 调用失败
【发布时间】:2014-02-16 06:04:15
【问题描述】:

在带有 PHP 5.4.17 和 curl 7.30.0 的 Mac OS 10.9.1 上,此 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')));

运行 Mac OS 10.7.5 和 PHP 5.4.11 和 curl 7.21.4 的旧系统正确发送授权标头。我尝试了 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 上,它们都无法发送除非我手动设置授权标头。为什么?

【问题讨论】:

    标签: php macos curl


    【解决方案1】:

    这是错误的:

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

    使用引号,您正在尝试将字符串设置为选项。但是 CURL 使用 define()'d 常量,它们没有被引用。

    试试

    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    

    所以你使用的是实际的 CURL 常量,而不是看起来像常量的随机字符串。

    【讨论】:

    • 你说得对; CURLAUTH_BASIC 应该是一个常量,而不是字符串。但现在我想知道引用的版本是如何工作的。它在我每天使用了 5 年的图书馆里。
    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2018-11-05
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多