The BrowserKit Component

The BrowserKit Component

The BrowserKit component simulates the behavior of a web browser, allowing you to make requests, click on links and submit forms programmatically.

Note

In Symfony versions prior to 4.3, the BrowserKit component could only make internal requests to your application. Starting from Symfony 4.3, this component can also make HTTP requests to any public site when using it in combination with the HttpClient component.

Installation

  1. $ composer require symfony/browser-kit

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Basic Usage

See also

This article explains how to use the BrowserKit features as an independent component in any PHP application. Read the Symfony Functional Tests article to learn about how to use it in Symfony applications.

Creating a Client

The component only provides an abstract client and does not provide any backend ready to use for the HTTP layer. To create your own client, you must extend the AbstractBrowser class and implement the doRequest() method. This method accepts a request and should return a response:

  1. namespace Acme;
  2. use Symfony\Component\BrowserKit\AbstractBrowser;
  3. use Symfony\Component\BrowserKit\Response;
  4. class Client extends AbstractBrowser
  5. {
  6. protected function doRequest($request)
  7. {
  8. // ... convert request into a response
  9. return new Response($content, $status, $headers);
  10. }
  11. }

For a simple implementation of a browser based on the HTTP layer, have a look at the Symfony\Component\BrowserKit\HttpBrowser provided by this component. For an implementation based on HttpKernelInterface, have a look at the Symfony\Component\HttpKernel\Client provided by the HttpKernel component.

Making Requests

Use the request() method to make HTTP requests. The first two arguments are the HTTP method and the requested URL:

  1. use Acme\Client;
  2. $client = new Client();
  3. $crawler = $client->request('GET', '/');

The value returned by the request() method is an instance of theSymfony\Component\DomCrawler\Crawler` class, provided by the DomCrawler component, which allows accessing and traversing HTML elements programmatically.

The jsonRequest() method, which defines the same arguments as the `request() method, is a shortcut to convert the request parameters into a JSON string and set the needed HTTP headers:

  1. use Acme\Client;
  2. $client = new Client();
  3. // this encodes parameters as JSON and sets the required CONTENT_TYPE and HTTP_ACCEPT headers
  4. $crawler = $client->jsonRequest('GET', '/', ['some_parameter' => 'some_value']);

New in version 5.3: The `jsonRequest() method was introduced in Symfony 5.3.

The xmlHttpRequest() method, which defines the same arguments as the `request() method, is a shortcut to make AJAX requests:

  1. use Acme\Client;
  2. $client = new Client();
  3. // the required HTTP_X_REQUESTED_WITH header is added automatically
  4. $crawler = $client->xmlHttpRequest('GET', '/');

The AbstractBrowser is capable of simulating link clicks. Pass the text content of the link and the client will perform the needed HTTP GET request to simulate the link click:

  1. use Acme\Client;
  2. $client = new Client();
  3. $client->request('GET', '/product/123');
  4. $crawler = $client->clickLink('Go elsewhere...');

If you need the Symfony\Component\DomCrawler\Link object that provides access to the link properties (e.g. $link->getMethod(),$link->getUri()), use this other method:

  1. // ...
  2. $crawler = $client->request('GET', '/product/123');
  3. $link = $crawler->selectLink('Go elsewhere...')->link();
  4. $client->click($link);

Submitting Forms

The AbstractBrowser is also capable of submitting forms. First, select the form using any of its buttons and then override any of its properties (method, field values, etc.) before submitting it:

  1. use Acme\Client;
  2. $client = new Client();
  3. $crawler = $client->request('GET', 'https://github.com/login');
  4. // find the form with the 'Log in' button and submit it
  5. // 'Log in' can be the text content, id, value or name of a <button> or <input type="submit">
  6. $client->submitForm('Log in');
  7. // the second optional argument lets you override the default form field values
  8. $client->submitForm('Log in', [
  9. 'login' => 'my_user',
  10. 'password' => 'my_pass',
  11. // to upload a file, the value must be the absolute file path
  12. 'file' => __FILE__,
  13. ]);
  14. // you can override other form options too
  15. $client->submitForm(
  16. 'Log in',
  17. ['login' => 'my_user', 'password' => 'my_pass'],
  18. // override the default form HTTP method
  19. 'PUT',
  20. // override some $_SERVER parameters (e.g. HTTP headers)
  21. ['HTTP_ACCEPT_LANGUAGE' => 'es']
  22. );

If you need the Symfony\Component\DomCrawler\Form object that provides access to the form properties (e.g. $form->getUri(),$form->getValues(), `$form->getFields()), use this other method:

  1. // ...
  2. // select the form and fill in some values
  3. $form = $crawler->selectButton('Log in')->form();
  4. $form['login'] = 'symfonyfan';
  5. $form['password'] = 'anypass';
  6. // submit that form
  7. $crawler = $client->submit($form);

Custom Header Handling

New in version 5.2: The `getHeaders() method was introduced in Symfony 5.2.

The optional HTTP headers passed to the request() method follows the FastCGI request format (uppercase, underscores instead of dashes and prefixed withHTTP). Before saving those headers to the request, they are lower-cased, withHTTP` stripped, and underscores turned to dashes.

If you’re making a request to an application that has special rules about header capitalization or punctuation, override the `getHeaders() method, which must return an associative array of headers:

  1. protected function getHeaders(Request $request): array
  2. {
  3. $headers = parent::getHeaders($request);
  4. if (isset($request->getServer()['api_key'])) {
  5. $headers['api_key'] = $request->getServer()['api_key'];
  6. }
  7. return $headers;
  8. }

Cookies

Retrieving Cookies

The AbstractBrowser implementation exposes cookies (if any) through a Symfony\Component\BrowserKit\CookieJar, which allows you to store and retrieve any cookie while making requests with the client:

  1. use Acme\Client;
  2. // Make a request
  3. $client = new Client();
  4. $crawler = $client->request('GET', '/');
  5. // Get the cookie Jar
  6. $cookieJar = $client->getCookieJar();
  7. // Get a cookie by name
  8. $cookie = $cookieJar->get('name_of_the_cookie');
  9. // Get cookie data
  10. $name = $cookie->getName();
  11. $value = $cookie->getValue();
  12. $rawValue = $cookie->getRawValue();
  13. $isSecure = $cookie->isSecure();
  14. $isHttpOnly = $cookie->isHttpOnly();
  15. $isExpired = $cookie->isExpired();
  16. $expires = $cookie->getExpiresTime();
  17. $path = $cookie->getPath();
  18. $domain = $cookie->getDomain();
  19. $sameSite = $cookie->getSameSite();

Note

These methods only return cookies that have not expired.

Looping Through Cookies

  1. use Acme\Client;
  2. // Make a request
  3. $client = new Client();
  4. $crawler = $client->request('GET', '/');
  5. // Get the cookie Jar
  6. $cookieJar = $client->getCookieJar();
  7. // Get array with all cookies
  8. $cookies = $cookieJar->all();
  9. foreach ($cookies as $cookie) {
  10. // ...
  11. }
  12. // Get all values
  13. $values = $cookieJar->allValues('http://symfony.com');
  14. foreach ($values as $value) {
  15. // ...
  16. }
  17. // Get all raw values
  18. $rawValues = $cookieJar->allRawValues('http://symfony.com');
  19. foreach ($rawValues as $rawValue) {
  20. // ...
  21. }

Setting Cookies

You can also create cookies and add them to a cookie jar that can be injected into the client constructor:

  1. use Acme\Client;
  2. // create cookies and add to cookie jar
  3. $cookie = new Cookie('flavor', 'chocolate', strtotime('+1 day'));
  4. $cookieJar = new CookieJar();
  5. $cookieJar->set($cookie);
  6. // create a client and set the cookies
  7. $client = new Client([], null, $cookieJar);
  8. // ...

History

The client stores all your requests allowing you to go back and forward in your history:

  1. use Acme\Client;
  2. $client = new Client();
  3. $client->request('GET', '/');
  4. // select and click on a link
  5. $link = $crawler->selectLink('Documentation')->link();
  6. $client->click($link);
  7. // go back to home page
  8. $crawler = $client->back();
  9. // go forward to documentation page
  10. $crawler = $client->forward();

You can delete the client’s history with the `restart() method. This will also delete all the cookies:

  1. use Acme\Client;
  2. $client = new Client();
  3. $client->request('GET', '/');
  4. // reset the client (history and cookies are cleared too)
  5. $client->restart();

Making External HTTP Requests

So far, all the examples in this article have assumed that you are making internal requests to your own application. However, you can run the exact same examples when making HTTP requests to external web sites and applications.

First, install and configure the HttpClient component. Then, use the Symfony\Component\BrowserKit\HttpBrowser to create the client that will make the external HTTP requests:

  1. use Symfony\Component\BrowserKit\HttpBrowser;
  2. use Symfony\Component\HttpClient\HttpClient;
  3. $browser = new HttpBrowser(HttpClient::create());

You can now use any of the methods shown in this article to extract information, click links, submit forms, etc. This means that you no longer need to use a dedicated web crawler or scraper such as Goutte:

  1. $browser = new HttpBrowser(HttpClient::create());
  2. $browser->request('GET', 'https://github.com');
  3. $browser->clickLink('Sign in');
  4. $browser->submitForm('Sign in', ['login' => '...', 'password' => '...']);
  5. $openPullRequests = trim($browser->clickLink('Pull requests')->filter(
  6. '.table-list-header-toggle a:nth-child(1)'
  7. )->text());

Learn more

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.