DEV Community

Mert Simsek
Mert Simsek

Posted on

Handling Cookie From Guzzle FileCookieJar

Today, in this article, I would like to mention about cookie concept of the Guzzle. I've looked over on internet about this issue but I couldn't even find clear solution on the documentation. Well, my scenario is like this, I would like to authenticate a system by using username and password. In addition to this, I want Guzzle to store cookie data into a json file. With this way, I refer this file to request for further queries.

First of all, I would like to show my auth method to request.



    /**
     * @param Client $client
     * @return array
     * @throws GuzzleException
     */
    public function auth(Client $client): array
    {
        try {
            $apiUrl = getenv('API_URL');
            $username = getenv('USERNAME');
            $password = getenv('PASSWORD');

            $postData = array('email' => $username, 'password' => $password, 'keep_logged_in' => true);

            $response = $client->request('POST', $apiUrl . '/rest/authenticate', [
                'json' => $postData,
                'cookies' => new FileCookieJar('/Users/mertsimsek/Development/app/assets/cookies.json')
            ]);
            $results = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);

            return ($results['success']) ? array('status' => true, 'message' => 'Authentication has set successfully.') : array('success' => false, 'message' => 'Authentication wasn\'t able to set.');
        } catch (RequestException $e) {
            return
                array(
                    'status' => false,
                    'message' => $e->getMessage()
                );
        }
    }


Enter fullscreen mode Exit fullscreen mode

By FileCookieJar I am able to store cookie data into a file as JSON format. Thus, I will read this file to further requests. I've created a new method to read this file.



    /**
     * @return CookieJar
     */
    public function getCookieJarFromFile(): CookieJar
    {
        $cookieData = json_decode(file_get_contents('/Users/mertsimsek/Development/app/assets/cookies.json'));
        foreach ($cookieData as $cookie) {
            //If there are multiple cookie data, you could filter according to your case
            $cookie = json_decode(json_encode($cookie), TRUE);
            $setCookie = new SetCookie($cookie);
        }

        $jar = new CookieJar();
        $jar->setCookie($setCookie);

        return $jar;
    }


Enter fullscreen mode Exit fullscreen mode

Well, from now on, I've a method to get cookie data from that file. Now, we could create a method to request new queries.As long as I request authpath, I am going to get this result and the json file will be created by Guzzle.

alt text

alt text

Right, we're able to request with this file to get data from APIs clearly. As you see, I get the cookie data from that file and I request by using Guzzle library.



    /**
     * @param Client $client
     * @return array
     * @throws GuzzleException
     */
    public function requestToApi(Client $client): array
    {
        $apiUrl = getenv('API_URL');
        $postData = array();

        try {
            $jar = $this->getCookieJarFromFile();

            $response = $client->request('GET', $apiUrl . '/rest/getUsers', [
                'json' => $postData,
                'cookies' => $jar
            ]);
            $results = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);

            return ($results['success']) ? array('status' => true, 'message' => 'Authentication has set successfully.') : array('success' => false, 'message' => 'Authentication wasn\'t able to set.');
        } catch (RequestException $e) {
            return
                array(
                    'status' => false,
                    'message' => $e->getMessage()
                );
        }
    }


Enter fullscreen mode Exit fullscreen mode

Hopefully, this article truly helps you to use FileCookieJar. If you have a trouble, don't hesitate to stay in touch.

Top comments (2)

Collapse
 
angelincalu profile image
Angelin Calu

I believe this is really not needed. You could just use the same cookie jar.

Collapse
 
cheapapp_net profile image
CheapApp.Net

This is a great tutorial. Unfortunately, I could not get success.