Handling Cookie From Guzzle FileCookieJar
Tags: php, beginnes, webdev
Published: 2019-04-09 11:24:59

---
title: Handling Cookie From Guzzle FileCookieJar
published: true
description: We'll be learned about using the cookie concept of the Guzzle
tags: #php #beginnes #webdev
---

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.

```php
    /**
     * @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()
                );
        }
    }
```

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.

```php
    /**
     * @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;
    }
```

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 `auth`path, I am going to get this result and the json file will be created by Guzzle.

![alt text](https://thepracticaldev.s3.amazonaws.com/i/fcrrh5st9cpy4mfmur22.png "")

![alt text](https://thepracticaldev.s3.amazonaws.com/i/djcgxrvnv3zjiz7m0djp.png "")

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.

```php
    /**
     * @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()
                );
        }
    }
```

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