【发布时间】:2016-08-22 17:17:28
【问题描述】:
我有一些代码请求从 Jive 的 API 获取数据。我在 MAMP 上运行此代码,它允许我运行 PHP 5.6.10 或 PHP 7.0.0。使用 PHP5,我得到了成功的响应。使用 PHP 7 我得到 401 Unauthorized。
相关函数在这里:
protected function sendRequest($method, $url, $auth = null) {
global $CFG;
$options = func_num_args() === 4 ? func_get_arg(3) : array();
$http = array(
'max_redirects' => 0,
'request_fulluri' => 1,
'ignore_errors' => true,
'method' => $method,
'header' => array()
);
if (!is_null($auth)) {
array_push($http['header'], 'Authorization: ' . $auth);
}
if (($method === 'PUT' || $method === 'POST') && isset($options['content'])) {
$http['content'] = $options['content'];
array_push($http['header'], 'Content-length: ' . strlen($options['content']));
array_push($http['header'], 'Content-Type: application/json');
}
var_dump($http);echo('<hr/>');
$context = stream_context_create(array( 'http' => $http ));
var_dump(stream_context_get_options($context));echo('<hr/>');
$fp = fopen($url, 'rb', false, $context);
if (! $fp) {
throw new \Exception('Request failed: $php_errormsg');
}
$metadata = stream_get_meta_data($fp);
$content = stream_get_contents($fp);
$responseCode = (int)explode(' ', $metadata['wrapper_data'][0])[1];
fclose($fp);
return array (
'metadata' => $metadata,
'content' => $content,
'status' => $responseCode
);
}
两个 PHP 版本的 var_dump 调用产生相同的结果。我得到的回应是:
{
"metadata": {
"wrapper_data": [
"HTTP/1.0 401 Unauthorized",
"Server: Apache",
"X-Jive-Request-Id: 6c433c20-688a-11e6-b332-005056a4250c",
"X-Jive-Flow-Id: 6c433c21-688a-11e6-b332-005056a4250c",
"X-Frame-Options: SAMEORIGIN",
"Expires: Mon, 22 Aug 2016 17:04:01 GMT",
"Cache-Control: no-store, no-cache, must-revalidate, private, max-age=0",
"X-JSL: D=1754 t=1471885441249342",
"Content-Type: text/plain",
"Date: Mon, 22 Aug 2016 17:04:01 GMT",
"Connection: close",
"Set-Cookie: jive.login.ts=1471885441250; Path=/; Secure; HttpOnly;HttpOnly",
"Set-Cookie: X-JCAPI-Token=pTVEn2P4; Path=/; Secure; HttpOnly",
"Set-Cookie: BIGipServerpool_sandbox.jiveon.com=25472522.20480.0000; path=/"
],
"wrapper_type": "http",
"stream_type": "tcp_socket/ssl",
"mode": "rb",
"unread_bytes": 0,
"seekable": false,
"uri": "https://sandbox.jiveon.com/api/core/v3/activities?after=2016-08-22T17:01:14%2b0000&count=500",
"crypto": {
"protocol": "TLSv1",
"cipher_name": "ECDHE-RSA-AES256-SHA",
"cipher_bits": 256,
"cipher_version": "TLSv1/SSLv3"
},
"timed_out": false,
"blocked": true,
"eof": false
},
"content": "",
"status": 401,
"success": false
}
通过https://requestb.in可以看到PHP7版本不包含授权头
PHP 5.6.10 和 PHP 7 之间发生了哪些变化导致了这种情况?我如何解决它?
编辑:删除一些红鲱鱼文本并添加请求箱结果。
【问题讨论】:
-
对于初学者,我在 PHP5 请求中看到
"WWW-Authenticate: Basic realm=\"Jive SBS\"",但在 PHP7 中没有看到。我从来没有使用过这个 API,所以也许你应该联系他们。有可能 PHP7 发送了他们的 API 认为是黑客攻击的不同标头? -
谢谢。这给了我一个想法。我将尝试将请求定位到我控制的端点,看看有什么不同。
-
NP,要考虑的另一件事是使用 CURL 而不是 fopen(),因为看起来您只是在与 JSON API 交互,而 fopen() 在处理时只是 CURL 的包装器网址。我怀疑使用 fopen() 有什么好处,但我不是专家,祝你好运!
-
好的,我已经确认 PHP7 没有发送 Authorization 标头,但它包含在上下文中。我还测试了“foo:bar”的标题,也没有通过。
标签: php fopen php-7 http-status-code-401 php-5.6