cURL
is synchronous. So how do libraries like Guzzle send asynchronous web requests?
Guzzle allows you to send both asynchronous and synchronous requests using the same interface and no direct dependency on an event loop. This flexibility allows Guzzle to send an HTTP request using the most appropriate HTTP handler based on the request being sent.
You can also send requests synchronously by calling WdfRequestSend, but you have to format the request first by following the rules that are described in Sending I/O Requests Asynchronously. Sending I/O requests to an I/O target synchronously is simpler to program than sending I/O requests asynchronously.
Asynchronous request. If you use an asynchronous XMLHttpRequest , you receive a callback when the data has been received. This lets the browser continue to work as normal while your request is being handled.
Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);
One of the Guzzle's transport handlers is CurlMultiHandler
that uses PHP's curl_multi_*
functions which allows for asynchronous transfers.
The requests are launched asynchronously and the function curl_multi_select()
allows Guzzle
to wait until one of the curl requests receives data and process it.
The Guzzle CurlMultiHander wraps PHP's builtin curl_multi_* function which essentially wrap the cURL Multi API
From the cURL documents:
To use the multi interface, you must first create a 'multi handle' with curl_multi_init. This handle is then used as input to all further curl_multi_* functions.
With a multi handle and the multi interface you can do several simultaneous transfers in parallel. Each single transfer is built up around an easy handle. You create all the easy handles you need, and setup the appropriate options for each easy handle using curl_easy_setopt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With