0

我需要使用由 Wordpress 设置的客户端 cookie 发送file_get_contents()到 API 端点,以显示用户已登录到 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 。请看下面我的回答。

4

4 回答 4

1

cookie 应采用以下格式:Cookie: cookieone=value; cookietwo=value,即用分号和空格分隔,后面没有分号。循环遍历您的 cookie 数组,输出该格式,然后发送。

于 2012-07-31T19:37:44.247 回答
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,以便以登录用户的身份进行调用。

于 2012-08-01T01:09:48.207 回答
0

好的,正如您提到的,您应该使用cURL(部分是我个人的意见,我在禁止 URL 文件包装器的服务器配置方面有一些不好的经验)。

来自手册的报价:

如果启用了 fopen 包装器,则 URL 可以用作此函数的文件名。

因此,您可能会遇到代码无法正常工作的情况。另一方面,cURL它是为获取远程内容而设计的,并提供了对正在发生的事情、如何获取数据等的大量控制。

当您查看时,curl_setopt您可以看到可以设置的数量和详细程度(但您不必这样做,它只是在需要时可选)。

这是谷歌搜索后的第一个链接php curl set cookies,这是您开始的好地方......基本示例完全是微不足道的。

于 2012-07-31T19:49:57.933 回答
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 check”字符串之后的最后一个空格。

于 2016-03-08T01:02:46.297 回答