phpcurl

Stream response from CURL request without waiting for it to finish


I have a PHP script on my server that is making a request to another server for an image.

The script is accessed just like a regular image source like this:

<img src="http://example.com/imagecontroller.php?id=1234" />

Browser -> Script -> External Server

The script is doing a CURL request to the external server.

Is it possible to "stream" the CURL response directly back to the client (browser) as it is received on the server?

Assume my script is on a slow shared hosting server and the external server is blazing fast (a CDN). Is there a way to serve the response directly back to the client without my script being a bottleneck? It would be great if my server didn't have to wait for the entire image to be loaded into memory before beginning the response to the client.


Solution

  • Pass the -N/--no-buffer flag to curl. It does the following:

    Disables the buffering of the output stream. In normal work situations, curl will use a standard buffered output stream that will have the effect that it will output the data in chunks, not necessarily exactly when the data arrives. Using this option will disable that buffering.

    Note that this is the negated option name documented. You can thus use --buffer to enforce the buffering.