Skip to content

[BrowserKit][HttpClient] Add examples to set cookies in the request #17888

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions components/browser_kit.rst
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,25 @@ into the client constructor::
$client = new Client([], null, $cookieJar);
// ...

Sending Cookies
~~~~~~~~~~~~~~~

By setting the ``Cookie`` header value, you are able to send cookies with your
request thanks to the ``serverParameters`` argument of the
:method:`Symfony\\Component\\BrowserKit\\AbstractBrowser::request` method::

$client->request('GET', '/', [], [], [
'HTTP_COOKIE' => new Cookie('flavor', 'chocolate', strtotime('+1 day')),

// you're also able to pass a string instead
'HTTP_COOKIE' => 'flavor=chocolate; expires=Sat, 11 Feb 2023 12:18:13 GMT; Max-Age=86400; path=/'
]);

.. note::

All HTTP headers set with the ``serverParameters`` argument must be
prefixed by ``HTTP_``.

History
-------

Expand Down
15 changes: 15 additions & 0 deletions http_client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,21 @@ You can either handle cookies yourself using the ``Cookie`` HTTP header or use
the :doc:`BrowserKit component </components/browser_kit>` which provides this
feature and integrates seamlessly with the HttpClient component.

However, you're able to send cookies in your request. This is how you can do
so using :class:`Symfony\\Contracts\\HttpClient\\HttpClient`::

use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Cookie;

$client = HttpClient::create([
'headers' => [
'Cookie' => new Cookie('flavor', 'chocolate', strtotime('+1 day')),

// you're also able to pass a string instead
'Cookie' => 'flavor=chocolate; expires=Sat, 11 Feb 2023 12:18:13 GMT; Max-Age=86400; path=/'
],
]);

Redirects
~~~~~~~~~

Expand Down