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?
Fake a request abortion using
CURL
setting a lowCURLOPT_TIMEOUT_MS
set
ignore_user_abort(true)
to keep processing after the connection closed.With this method no need to implement connection handling via headers and buffer too dependent on OS, Browser and PHP version
Master process
Background process
NB
Resources
curl timeout less than 1000ms always fails?
http://www.php.net/manual/en/function.curl-setopt.php#104597
http://php.net/manual/en/features.connection-handling.php
let me show you my way :)
needs nodejs installed on the server
(my server sends 1000 https get request takes only 2 seconds)
url.php :
urlscript.js >
You can use non-blocking sockets and one of pecl extensions for PHP:
You can use library which gives you an abstraction layer between your code and a pecl extension: https://github.com/reactphp/event-loop
You can also use async http-client, based on the previous library: https://github.com/reactphp/http-client
See others libraries of ReactPHP: http://reactphp.org
Be careful with an asynchronous model. I recommend to see this video on youtube: http://www.youtube.com/watch?v=MWNcItWuKpI
The swoole extension. https://github.com/matyhtf/swoole Asynchronous & concurrent networking framework for PHP.
You can use this library: https://github.com/stil/curl-easy
It's pretty straightforward then:
Below you can see console output of above example. It will display simple live clock indicating how much time request is running: