Ad

Hold Guzzle Cookies Across Multiple Requests

- 1 answer

I'd like to create a proxy for a specific site so users, which can't access that site (due to the sites IP being blocked by their ISP for instance), can access it through my proxy. I would use Guzzle to make HTTP requests, exchange all links to my own site and then display it.

I know this is not exactly ideal, but for a start it seemed to work and I don't expect hundreds of people to use it. It should just be in place, in case someone does need it.

The problem I am having is cookies. The other site obviously uses sessions/cookies to keep the users logged in. Basically there's nothing you can do without being logged in. I already pass all form data and such to the HTTP request, but cookies keep throwing me out.

protected function makeRequest($path, $parameters)
{
    $cookieJar = new CookieJar;

    $client = new Client(['base_uri' => self::$staticURL]);
    $response = $client->request($parameters['method'], self::buildUrl($path), [
        'form_params' => Request::all(),
        'cookies'     => $cookieJar,
    ]);

    // Session::flash can only flash strings, but CookieJar is not serializable.
    // Session::flash('cookie', $cookieJar);

    return self::replaceURLs($parameters['original'], self::$staticURL, $response->getBody(), $parameters['base']);
}

As you can see I am passing a CookieJar instance to the request, as it was mentioned in the documentation. With this, I am able to log into the site, but as soon as I click another link, it throws me back out. So I assume it doesn't save the cookie across multiple requests.

Which ways do I have to do that?

Ad

Answer

I thought the cookies option required an instance of type CookieJar, which is not the case. What it requires is a CookieJarInterface. Looking further into the Guzzle library I found the FileCookieJar, which is saved in a file.

I now generate an ID for each session and write the cookies into a file using that ID. That way each user of my page has the cookies saved and they get loaded on each subsequent request.

protected function makeCookiePath()
{
    $sessionId = $this->request->session()->get('cookie.id', str_random(40));

    $this->request->session()->put('cookie.id', $sessionId);
    return storage_path('cookies/' . $sessionId);
}

protected function makeRequest($path, $parameters)
{
    $cookieJar = new FileCookieJar($this->makeCookiePath(), true);

    // ...
}
Ad
source: stackoverflow.com
Ad