Failed to send cookie with Guzzle request

I have a PHP script that needs to fetch a CSV file from an application. There is an API for the application that allows the script to bid, which gives the script a session cookie for authentication. Then I need to make a GET request to get the CSV file (which the API doesn't support).

Using curl directory works:

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

      

This fetches the CSV file using the session id obtained from the API login and passed through the coookie.

Now, I would like to do the same using Guzzle, but I will return the login page instead. This is the code I'm using:

$client = new Guzzle\Http\Client();
$request = $client->get(
    $url,
    [
        'cookies' => ['PHPSESSID' => $session_id_from_api],
    ]
);
$response = $client->send($request);
echo $response->getBody(true);

      

This gives me a login page, so the GET for the application does not recognize the session defined by the cookie.

Is there something else that needs to be done in order for the cookie and the value I specify to be sent to the remote application?

Edit: Looking at $request->getRawHeaders()

, I can see this line in the headers:

cookies: vec6nb1egvvui6op7qr7b0oqf6

      

This is obviously not the case. The documentation for my version of Guzzle gives the following example:

// Enable cookies and send specific cookies
$client->get('/get', ['cookies' => ['foo' => 'bar']]);

      

who looks at me so that I agree that I am going to goose.

Just to be clear, I'm not trying to manage cookies both ways across multiple requests, so there is no need to store cookies. I have a cookie name and value (from another source) and I just want to make sure the name and value are sent to the destination for one GET request. I'm not trying to "maintain a session", but somehow I have a session passed to me from another part of the application (not with Guzzle) and I need to set my Guzzle request to use it.

+3


source to share


1 answer


Well it looks like it works. Guzzle did not send the cookie, not being sure that the domain he sent was correct:



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

      

+9


source







All Articles