我有一个PHP脚本需要从应用程序中获取CSV文件.应用程序有一个API允许脚本进入,这为脚本提供了一个用于身份验证的会话cookie.然后我需要做一个GET请求来获取CSV文件(API不支持).
使用curl目录工作:
$c = curl_init($url); curl_setopt($c, CURLOPT_COOKIE, 'PHPSESSID=' . $session_id_from_api); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $csv_file = curl_exec($c); echo $csv_file;
使用从API登录获得的会话ID获取CSV文件并通过coookie传递.
现在,我想使用Guzzle做同样的事情,但我只是返回登录页面.这是我正在使用的代码:
$client = new Guzzle\Http\Client(); $request = $client->get( $url, [ 'cookies' => ['PHPSESSID' => $session_id_from_api], ] ); $response = $client->send($request); echo $response->getBody(true);
这给了我登录页面,因此应用程序的GET无法识别cookie定义的会话.
还有什么我需要做的,以确保我指定的cookie和值被发送到远程应用程序?
编辑:看$request->getRawHeaders()
,我在标题中看到这一行:
cookies: vec6nb1egvvui6op7qr7b0oqf6
这显然是不对的.我的Guzzle版本的文档给出了这个例子:
// Enable cookies and send specific cookies $client->get('/get', ['cookies' => ['foo' => 'bar']]);
这看起来与我传递给Guzzle的内容一致.
为了清楚起见,我不是试图通过多个请求在两个方向上管理cookie,因此不需要存储任何cookie.我有一个cookie名称及其值(来自其他来源),我只想确保将名称和值发送到目标以获得单个GET请求.我不是试图"维持一个会话",但在某种程度上,我正在从应用程序的另一部分(而不是Guzzle)传递给我,并且需要设置我的Guzzle请求才能使用它.
好吧,这似乎有效.Guzzle没有发送cookie而没有确定它发送给它的域是正确的:
// Set up a cookie - name, value AND domain. $cookie = new Guzzle\Plugin\Cookie\Cookie(); $cookie->setName('PHPSESSID'); $cookie->setValue($session_id_from_api); $cookie->setDomain($domain_of_my_service_url); // Set up a cookie jar and add the cookie to it. $jar = new Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar(); $jar->add($cookie); // Set up the cookie plugin, giving it the cookie jar. $plugin = new Guzzle\Plugin\Cookie\CookiePlugin($jar); // Register the plugin with the client. $client->addSubscriber($plugin); // Now do the request as normal. $request = $client->get($url); $response = $client->send($request); // The returned page body. echo $response->getBody(true);