为 Guzzle CookieJar 设置 cookie
Setting up cookies for Guzzle CookieJar
我正在 PHP 中对需要身份验证的站点进行单元测试。身份验证是基于 cookie 的,因此我需要能够将这样的 cookie 放入 cookie 罐中:
[ 'user_token' => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' ]
Web 应用程序然后可以将这个已知良好的令牌用于测试数据,并且能够在测试条件下进行身份验证以与数据装置交互。
此外,它必须是一个安全 cookie,我(显然)需要设置域。
问题是:我不知道如何制作和放置这个饼干并将其粘在罐子里。你是怎么做到的?
简单的例子。此代码将 cookie 保存在一个文件中,并在您下次执行脚本时将其加载回来
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\FileCookieJar;
// file to store cookie data
$cookieFile = 'cookie_jar.txt';
$cookieJar = new FileCookieJar($cookieFile, TRUE);
$client = new Client([
'base_uri' => 'http://example.com',
// specify the cookie jar
'cookies' => $cookieJar
]);
// guzzle/cookie.php, a page that returns cookies.
$response = $client->request('GET', 'simple-page.php');
session cookies are not stored automatically. To store the php
session cookie we must set the second parameter to TRUE.
$cookieJar = new FileCookieJar($cookieFile, TRUE);
引用
The source code 提供了我需要的答案。
CookieJar class 提供了一种从关联数组构建 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
]);
我正在 PHP 中对需要身份验证的站点进行单元测试。身份验证是基于 cookie 的,因此我需要能够将这样的 cookie 放入 cookie 罐中:
[ 'user_token' => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' ]
Web 应用程序然后可以将这个已知良好的令牌用于测试数据,并且能够在测试条件下进行身份验证以与数据装置交互。
此外,它必须是一个安全 cookie,我(显然)需要设置域。
问题是:我不知道如何制作和放置这个饼干并将其粘在罐子里。你是怎么做到的?
简单的例子。此代码将 cookie 保存在一个文件中,并在您下次执行脚本时将其加载回来
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\FileCookieJar;
// file to store cookie data
$cookieFile = 'cookie_jar.txt';
$cookieJar = new FileCookieJar($cookieFile, TRUE);
$client = new Client([
'base_uri' => 'http://example.com',
// specify the cookie jar
'cookies' => $cookieJar
]);
// guzzle/cookie.php, a page that returns cookies.
$response = $client->request('GET', 'simple-page.php');
session cookies are not stored automatically. To store the php session cookie we must set the second parameter to TRUE.
$cookieJar = new FileCookieJar($cookieFile, TRUE);
引用
The source code 提供了我需要的答案。
CookieJar class 提供了一种从关联数组构建 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
]);