为Guzzle CookieJar设置Cookie [英] Setting up cookies for Guzzle CookieJar

查看:599
本文介绍了为Guzzle CookieJar设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PHP对需要身份验证的站点进行单元测试。身份验证基于cookie,因此我需要能够将这样的cookie放入cookie jar:

  ['user_token' => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'] 

然后,Web应用程序可以使用此已知的良好令牌来测试数据,并且将能够在测试条件下进行身份验证以与数据固定装置进行交互。



此外,它必须是安全的cookie,而且我(显然)需要设置域。 / p>

问题是:我不知道如何制作和设置此cookie并将其粘贴在罐子中。

解决方案

源代码提供了我所需的答案。



CookieJar类提供了一种从关联数组构建cookie的方法。例如:

  $ domain =‘example.org’; 
$ values = [’users_token'=> ‘2c26b46b68ffc68ff99b453c1d30113413422d706483bfa0f98a5e886266e7ae’];

$ cookieJar = \GuzzleHttp\Cookie\CookieJar :: fromArray($ values,$ domain);

$ client = new \GuzzleHttp\Client([
'base_uri'=>'https://example.org',
'cookies'=> $ cookieJar
]);


I am doing unit testing in PHP for a site that requires authentication. Authentication is cookie based, so I need to be able to put a cookie like this in the cookie jar:

[ 'user_token' => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' ] 

The web application can then use this known good token for the testing data, and will be able to authenticate under testing conditions to interact with the data fixtures.

Also, it must be a secure cookie, and I (obviously) need to set the domain.

Problem is: I don't know how to make and set this cookie and stick it in the jar. How do you do that?

解决方案

The source code provided the answer I needed.

The CookieJar class provides a method for building cookies from an associative array. Example:

$domain = 'example.org';
$values = ['users_token' => '2c26b46b68ffc68ff99b453c1d30113413422d706483bfa0f98a5e886266e7ae'];

$cookieJar = \GuzzleHttp\Cookie\CookieJar::fromArray($values, $domain);

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://example.org',
    'cookies'  => $cookieJar 
]);

这篇关于为Guzzle CookieJar设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆