Guzzle for HTTP POST authentication and form submission with Symfony 2.0

I’ve been helping out a co-worker with a small PHP library he’s working on which will eventually automate Drupal Security Advisory emails through to a central drupal “management” site, which knows about all sites that we work on, and automatically create “work requests” and allocate them to people so that we can easily track security vulnerabilities that need fixing! The work request API was missing a vital component - creating a new work request. So that was my job.

Well…this works but is less than ideal. It’s long, boring, and it hurts my eyes.

Enter Guzzle:

“Guzzle gives PHP developers complete control over HTTP requests while utilizing HTTP/1.1 best practices. Guzzle’s HTTP functionality is a robust framework built on top of the PHP libcurl bindings.”

Using the Guzzle HTTP Client and Cookie plugins, I was able to simplify this a lot.

First we set up the Guzzle client and add an empty CookiePlugin object as a “subscriber” on the HTTP Client. For more info on this see the Guzzle HTTP Client documentation

// Add this to allow your app to use Guzzle and the Cookie Plugin.use Guzzle\Http\Client as GuzzleClient;use Guzzle\Plugin\Cookie\Cookie;use Guzzle\Plugin\Cookie\CookiePlugin;use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;$httpClient = new GuzzleClient('https://example.com/');$httpClient->setSslVerification(FALSE);$cookieJar = new ArrayCookieJar();// Create a new cookie plugin$cookiePlugin = new CookiePlugin($cookieJar);// Add the cookie plugin to the client$httpClient->addSubscriber($cookiePlugin);

How easy was that? Now that I know how to use this library I can see the amazing opportunities with it. Drupal 8 core is utilising this as a replacement to the archaic drupal_http_request, the issue can be seen here, I can’t wait to see what other awesome features D8 gets from Symfony!