Is there a way in PHP to make asynchronous HTTP calls? I don't care about the response, I just want to do something like file_get_contents()
, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or triggering long processes.
Any ideas?
this needs php5, I stole it out of docs.php.net and edited the end.
I use it for monitoring when an error happens on a clients site, it sends data off to me without holding up the output
If you control the target that you want to call asynchronously (e.g. your own "longtask.php"), you can close the connection from that end, and both scripts will run in parallel. It works like this:
I have tried this, and it works just fine. But quick.php won't know anything about how longtask.php is doing, unless you create some means of communication between the processes.
Try this code in longtask.php, before you do anything else. It will close the connection, but still continue to run (and suppress any output):
The code is copied from the PHP manual's user contributed notes and somewhat improved.
ReactPHP async http client
https://github.com/shuchkin/react-http-client
Install via Composer
Async HTTP GET
Run php in CLI-mode
The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from How do I make an asynchronous GET request in PHP?
Here is a working example, just run it and open storage.txt afterwards, to check the magical result
As of 2018, Guzzle has become the defacto standard library for HTTP requests, used in several modern frameworks. It's written in pure PHP and does not require installing any custom extensions.
It can do asynchronous HTTP calls very nicely, and even pool them such as when you need to make 100 HTTP calls, but don't want to run more than 5 at a time.
Concurrent request example
See http://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests