ledy
ledy

Reputation: 1617

PHP: curl and stream forwarding

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?

Upvotes: 12

Views: 11566

Answers (2)

Nithi2023
Nithi2023

Reputation: 433

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);

Upvotes: 13

Andrey Volk
Andrey Volk

Reputation: 3549

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

Upvotes: 6

Related Questions