我需要使用Wordpress设置的客户端cookie向API端点发送file_get_contents()
,以显示用户已登录到wordpress站点。我知道我需要大致如下使用stream_context_create()
:
$cookies = ??? //THIS IS THE QUESTION (see answer below)!
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: {$cookies}\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://example.dev/api/autho/', false, $context);
正如您从第一行的评论中看到的那样,我坚持如何发送此请求以便发送正确的cookie。我知道发送了正确的cookie,因为我可以打印$_COOKIES
并在那里看到它们。但是如果我尝试将相同的数组插入到标题中,它就不起作用。
提前致谢!
ps:我已经读过我应该使用cURL
这个,但我不确定为什么,我不知道如何使用它...但我对这个想法持开放态度。
更新: 我得到了这个工作。这与我正在做的事情基本相同,还有另一个重要的cookie。请参阅下面的答案。
答案 0 :(得分:1)
Cookie应采用以下格式:Cookie: cookieone=value; cookietwo=value
,即以分号和空格分隔,不带有分号。循环遍历您的cookie数组,输出该格式并发送它。
答案 1 :(得分:1)
事实证明我正确地做到了,但我不知道 WP需要发送第二个Cookie 才能让请求正常运行。
以下是适用于我的代码:
$cookies = $_COOKIE;
$name;
$value;
foreach ($_COOKIE as $key => $cookie ) {
if ( strpos( $key, 'wordpress_logged_in') !== FALSE ) {
$name = $key;
$value = $cookie;
}
}
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: {$key}={$cookie}; wordpress_test_cookie=WP Cookie check \r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://mydomain.dev/api/autho/', false, $context);
var_dump($file);
这与你在我的问题中看到的基本相同,但有一个重要的补充:wordpress_test_cookie=WP Cookie check
。我没有在任何地方看到过它,但是WP需要这个cookie以及实际的wordpress_logged_in cookie,以便调用以登录用户的身份发生。
答案 2 :(得分:0)
好的,正如您所提到的那样,您应该使用cURL
(部分是我的个人意见,我对服务器配置有一些不良经验,禁止使用URL文件包装)。
来自manual的引用:
如果fopen,URL可以用作此函数的文件名 包装器已启用。
所以你可能会发现代码不起作用。另一方面,cURL
用于获取远程内容,并提供对正在进行的操作,如何获取数据等的大量控制。
当你看curl_setopt
时,你可以看到你可以设置多少以及多少详细的东西(但你不需要,它只是在你需要时可选)。
点击the first link之后的php curl set cookies
,这是你开始的好地方......基本的例子非常简单。
答案 3 :(得分:0)
$cookies = $_COOKIE;
foreach ($_COOKIE as $key => $cookie ) {
if ( strpos( $key, 'wordpress_logged_in') !== FALSE ) {
$name = $key;
$value = $cookie;
break;
}
}
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: {$key}={$cookie}; wordpress_test_cookie=WP Cookie check\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://mydomain.dev/api/autho/', false, $context);
var_dump($file);
我没有要点评论,所以我从emersonthis读了一些代码。为了在我的配置(php 7.0.3,wordpress 4.4.2)下工作,我必须删除" WP Cookie检查后的最后一个空格"字符串。