I am trying to perform multiple POST
REST Call. The catch: doing multiple POST calls at the same time. I am fully aware and have worked with the library guzzle
but I haven't figured away to do this properly. I can perform GET
calls asynchronously but nothing at the same level for POST
calls. Then I came across pthreads
and I read through the documentation and was a bit confused on how to even start it off. I have compiled php
with the pthreads
extension.
Could someone advise how to perform multiple POST
calls at the same time and be able to gather the responses for later manipulation?
The below is a basic implementation that loops and waits. Very slow overall.
$postDatas = [
['field' => 'test'],
['field' => 'test1'],
['field' => 'test2'],
];
foreach ($postDatas as $postData) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.apisite.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($postData),
CURLOPT_HTTPHEADER => [
"cache-control: no-cache",
"connection: keep-alive",
"content-type: application/json",
"host: some.apisite.com",
],
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}