5

I was wondering what the best way to do concurrent HTTP requests in PHP? I have a lot of data to get and i'd rather do multiple requests at once to retrieve it all.

Does anybody know how I can do this? Preferably in an anonymous/callback function mannor...

Thanks,

Tom.

tarnfeld
  • 25,992
  • 41
  • 111
  • 146
  • 2
    Like [`curl`](http://php.net/curl) the [`http`](http://php.net/http) extension also provides for concurrent requests, using the [`HttpRequestPool`](http://php.net/HttpRequestPool) class (which in turn just uses curl behind the scenes). – mario Oct 06 '11 at 23:36
  • Possible duplicate: http://stackoverflow.com/questions/1240267/asynchronous-http-requests-in-php – igorw Oct 06 '11 at 23:37
  • possible duplicate of [Parallel HTTP requests in PHP using PECL HTTP classes \[Answer: HttpRequestPool class\]](http://stackoverflow.com/questions/168951/parallel-http-requests-in-php-using-pecl-http-classes-answer-httprequestpool-cl) – mario Oct 06 '11 at 23:37

4 Answers4

12

You can use curl_multi, which internally fires off multiple separate requests under a single curl handle.

But otherwise PHP itself not in any way/shape/form "multithreaded" and will not allow things to run in parallel, except via gross hacks (multiple parallel scripts, one script firing up multiple background tasks via exec(), etc...).

Marc B
  • 356,200
  • 43
  • 426
  • 500
2

You can try either curl_multi() or use a lower level function socket_select()

Alexei Tenitski
  • 9,030
  • 6
  • 41
  • 50
1

you can use HttpRequestPool http://www.php.net/manual/de/httprequestpool.construct.php

$multiRequests = array(
  new HttpRequest('http://www.google.com', HttpRequest::METH_GET),
  new HttpRequest('http://www.yahoo.com', HttpRequest::METH_GET)
  new HttpRequest('http://www.bing.com', HttpRequest::METH_GET)
);

$pool = new HttpRequestPool();
foreach ($multiRequests as $request)
{
  $pool->attach($request);
}

$pool->send();

foreach($pool as $request) 
{
  echo $request->getResponseBody();
}
Tobias Gassmann
  • 11,399
  • 15
  • 58
  • 92
  • I am getting this error while testing this code : Fatal error: Class 'HttpRequest' not found. – Vijaysinh Parmar May 19 '16 at 04:47
  • You are probably using version 2 of pecl_http. In case you want to use HttpRequest you need to install pecl_http 1.7.6, I think. Version 2 has been completly rewritten years ago, nevertheless the documentation on php.net refers to version 1 – Tobias Gassmann May 19 '16 at 05:21
1

Or if you want you can send you data as json. In php you can defragment it into all the values again. for eg.

xhttp.open("GET", "gotoChatRoomorNot.php?q=[{"+str+"},{"+user1+"},{"+user2"}]", true);

and in php you can follow this to get your data back: How do I extract data from JSON with PHP?

So make a string in json format and send the entire thing through http. I think you can perform the same kind of behaviour with xml, but i am not aware of xml

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29