David
David

Reputation: 36404

PHP get_file_contents asynchronously

I just wondered if anyone had managed to get the contents of a remote URL asynchronously, work on it and then output it to the current document without using AJAX.

Upvotes: 2

Views: 795

Answers (3)

smassey
smassey

Reputation: 5931

Not with file_get_contents, no. Alternatively you can use the CURL extension and their non-blocking IO capabilities. All of this is available via the Multi Handlers of CURL. It's 'async' in the sense that you may poll the result and continue processing on other things if the result isn't ready to be read. This makes it 'async' in the sense that you're never blocking and waiting for the response, as long as there's work to be done - do it.. What's hard to understand for some people is the difference between async and non-blocking, in most cases with PHP what you really want is some sort of NB I/O. Given a few abstraction layers you can really come up with a nice IO callback interface with all the fun of anon functions, but thats another story..

See http://www.php.net/manual/en/function.curl-multi-init.php this is where it starts, the example included is great See http://www.php.net/manual/en/function.curl-multi-exec.php See http://www.php.net/manual/en/function.curl-multi-select.php for the NB poller

This guy avoids the ease of curl and goes straight to handling the http protocol which is yet another solution https://segment.io/blog/how-to-make-async-requests-in-php/ but requires a bit more of knowledge of the socket api.

Cheers

Upvotes: 2

Tyron
Tyron

Reputation: 1976

What you can do is create non blocking socket connections in PHP, which means your code can work on something else (e.g. print out HTML + flush() to the Browser) while the data from your connection is loading, then poll it later.

Just google for 'php asynchronous sockets'

Upvotes: 0

Alexandru R
Alexandru R

Reputation: 8833

PHP is single threaded. You have to use browser capabilities to fork another process.

Javascript can be asynchronously and you need it for your case.

Upvotes: 2

Related Questions