The BrowserKit Component

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

Note

In Symfony versions prior to 4.3, the BrowserKit component could only makeinternal requests to your application. Starting from Symfony 4.3, thiscomponent can also make HTTP requests to any public sitewhen 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 mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Basic Usage

This article explains how to use the BrowserKit features as an independentcomponent in any PHP application. Read the Symfony Functional Testsarticle 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 backendready to use for the HTTP layer.

To create your own client, you must extend the abstract Client class andimplement the doRequest() method.This method accepts a request and should return a response:

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

For a simple implementation of a browser based on the HTTP layer, have a lookat Goutte. For an implementation based on HttpKernelInterface, havea look at the Client provided bythe HttpKernel component.

Making Requests

Use the request() method tomake HTTP requests. The first two arguments are the HTTP method and the requestedURL:

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

The value returned by the request() method is an instance of theCrawler class, provided by theDomCrawler component, which allows accessingand traversing HTML elements programmatically.

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

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

The Client object is capable of simulating link clicks. Pass the textcontent of the link and the client will perform the needed HTTP GET request tosimulate the link click:

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

If you need the Link object thatprovides 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 Client object is also capable of submitting forms. First, select theform using any of its buttons and then override any of its properties (method,field values, etc.) before submitting it:

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

If you need the Form object thatprovides access to the form properties (e.g. $form->getUri(),$form->getValues(), $form->getFields()), use this other method:

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

Cookies

Retrieving Cookies

The Client implementation exposes cookies (if any) through aCookieJar, which allows you to store andretrieve any cookie while making requests with the client:

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

Note

These methods only return cookies that have not expired.

Looping Through Cookies

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

Setting Cookies

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

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

History

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

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

You can delete the client's history with the restart() method. This willalso delete all the cookies:

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

Making External HTTP Requests

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

First, install and configure the HttpClient component.Then, use the HttpBrowser to createthe client that will make the external HTTP requests:

  1. use Symfony\Component\BrowserKit\HttpBrowser;
  2. use Symfony\Component\HttpClient\HttpClient;
  3.  
  4. $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 adedicated web crawler or scraper such as Goutte:

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

New in version 4.3: The feature to make external HTTP requests was introduced in Symfony 4.3.

Learn more