如何与Wordpress用户一起使用file_get_contents()';s饼干


How to use file_get_contents() with a Wordpress user's cookies

我需要向API端点发送一个file_get_contents(),其中包含Wordpress设置的客户端cookie,以显示用户已登录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应采用以下格式:Cookie: cookieone=value; cookietwo=value,即用分号和不带尾随分号的空格分隔。循环浏览cookie数组,输出该格式并发送。

事实证明我做得很正确,但我不知道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_loged_in cookie,以便作为登录用户进行调用。

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

引用手册:

如果fopen已启用包装器。

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

当你查看curl_setopt时,你可以看到你可以设置多少以及有多详细的东西(但你不必这样做,它只是在你需要的时候可选的)。

这是谷歌搜索php curl set cookies后的第一个链接,这是你开始的好地方。。。基本的例子都是微不足道的。

$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);

我没有什么要评论的,所以我读了Emerson的代码。为了在我的配置(php 7.0.3,wordpress 4.4.2)下工作,我不得不删除"WP Cookie检查"字符串后的最后一个空格。