12

Curl has lots of options that make it easier for my use-case to request data from another server. My script is similar to a proxy and so far it is requesting the data from another server and once the result data is complete, it's send to the client at once.

  1. user visits http://te.st/proxy.php?get=xyz

  2. proxy.php downloads xyz from external-server

  3. when the download is completed 100%, it will output the data

Now I wonder whether 2 and 3 can also be done in parallel (with php5-curl), like a "proxy stream" that forwards data on the fly without waiting for the last line.

If the file size is 20MB in average, this makes a significant difference.

Is there an option for this in curl?

2 Answers 2

13

Here is the code that actually streams the files instead of waiting for full file to buffer.

$url = YOUR_URL_HERE;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
    echo $data;
    ob_flush();
    flush();
    return strlen($data);
});
curl_exec($ch);
curl_close($ch);
Sign up to request clarification or add additional context in comments.

1 Comment

Total thuimbs up. Just worked first time and with digest auth too
6

Take a look at http://www.php.net/manual/en/function.curl-setopt.php#26239

Something like that (not tested):

function myProgressFunc($ch, $str){ 
    echo $str;
    return strlen($str);
} 

curl_setopt($ch, CURLOPT_WRITEFUNCTION, "myProgressFunc"); 

Read also ParallelCurl with CURLOPT_WRITEFUNCTION

1 Comment

Good but not perfect: it's buffered. This means that it may be used for file streaming, but when it is an event stream, latest events are hanging unreachable inside the curl (flush() doesn't help to echo them all). That's a pity. +1 to you anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.