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.
Curl is awesome(ly verbose), but Guzzle is awesomer
I initially implemented this using PHP’s curl functions:
Which works nicely, but requires quite a lot of code:
Notice after I execute the post I need to then parse the response, get the “Set-Cookie” headers and store those cookies to use in my next post request so I can successfully submit a form.
Now we can use the cookies in the new curl connection and post some data to a form.
Well…this works but is less than ideal. It’s long, boring, and it hurts my eyes.
“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
Now we login.
Notice that the URL provided to the client’s post() method is relative. Relative URLs will always merge into the base URL of the client. Guzzle’s HTTP Client docs explain this more
Guzzle automagically gets the Cookies set from the response and adds them to our client. We literally do nothing else and we can now post data using the same cookies as we got from our login attempt.
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!