1
votes

I am using Guzzle from my Laravel application to CURL in to another PHP application.

The problem I am having is that after making a subsequent CURL request, the session is not being persisted. This makes sense of course - since every CURL request will be a unique session.

So for example, in my target application, suppose I do this:

$_SESSION['action_id'] = 1234;

Then in my next request, I want to do:

$action_id = $_SESSION['action_id'];

I get an undefined index error. I have looked at the documentation page on cookies (https://docs.guzzlephp.org/en/latest/quickstart.html#cookies), which says:

You can set cookies to true in a client constructor if you would like to use a shared cookie jar for all requests.

So I have tried that as follows:

$client = new \GuzzleHttp\Client(['cookies' => true]);

But that didn't make any difference. In my target application, if I do var_dump($_COOKIES['PHPSESSID']) it returns null. $_COOKIE is always empty itself. If I do var_dump(session_id()) I get a different value every time. So this is where the problem lies - I need to have access to the same session when I make a subsequent request.

Does anyone know how I can accomplish this?

2
Try to pass your php session cookie header, like in this response stackoverflow.com/questions/63890456/… .Sergio Rinaudo

2 Answers

1
votes

I found the answer. The solution was to do this:

$jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
    [
        'PHPSESSID' => $request->session()->getId(),
    ],
    'example.org'
);

$client = new \GuzzleHttp\Client([
    'cookies'  => $jar,
]);

I am not sure why I have had to do it this way - essentially I am getting the session ID from my source application and using that to create the PHPSESSID cookie in the target application. Strange, but it's what has worked for me. Now when I do var_dump(session_id()) I get the same value on each request.

On the Guzzle GitHub issues page, someone had posted the following solution (https://github.com/guzzle/guzzle/issues/1400):

$jar = new SessionCookieJar('PHPSESSID', true);
$client = new Client(['cookies' => $jar]);

But this never worked for me. I was hoping it would, as it looks like it handles it automatically. Perhaps someone can shed some light on this?

1
votes

You need to start a php session first:

session_start();
$jar = new SessionCookieJar('CookieJar', true); //'CookieJar' is the PHP Session Variable where it will be saved the cookie, it's not the cookie key... $_SESSION['CookieJar']
$client = new Client(['cookies' => $jar]);