Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: curl and stream forwarding

Tags:

php

curl

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?

like image 709
ledy Avatar asked May 09 '13 12:05

ledy


2 Answers

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

like image 186
Andrey Volk Avatar answered Sep 28 '22 01:09

Andrey Volk


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);
like image 35
Nithi2023 Avatar answered Sep 28 '22 02:09

Nithi2023